You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@hugegraph.apache.org by "bitflicker64 (via GitHub)" <gi...@apache.org> on 2026/07/23 06:57:37 UTC
[PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
bitflicker64 opened a new pull request, #3105:
URL: https://github.com/apache/hugegraph/pull/3105
## Purpose of the PR
Fix a startup hang in kind/Kubernetes environments caused by `lsof` scanning an enormous file descriptor table.
## Main Changes
The startup script (`start-hugegraph.sh`) calls `check_port` before launching Java to verify the target port is free. The original implementation used `lsof -i :PORT`.
In kind/k8s pods, `ulimit -n` (max open file descriptors) can be set to ~1 billion. `lsof` tries to scan all possible file descriptors up to that limit, pegging CPU at 100% and never completing — blocking server startup entirely. Plain Docker with the same image is unaffected because its default `ulimit -n` is ~1024.
**`hugegraph-server/.../util.sh`**
- Replace `lsof -i :PORT` with Bash's `/dev/tcp` pseudo-device. This checks whether the port accepts a TCP connection without invoking `lsof`, avoiding the expensive file-descriptor scan under very large `nofile` limits and removing the dependency on the external `lsof` binary.
**`hugegraph-pd/.../util.sh` and `hugegraph-store/.../util.sh`**
- Remove `check_port` entirely — it is never called by the PD or Store startup scripts (confirmed with maintainer).
- Fix `command_available`: the original implementation used command substitution while redirecting the command output to `/dev/null`, so the substitution always produced an empty result. This caused the function to report commands as available regardless of whether they existed, affecting `get_ip` and `download`.
## Verifying these changes
- [ ] Already covered by existing tests, such as *(please modify tests here)*.
- [x] Need tests and can be verified as follows:
- Start HugeGraph Server in a kind/Kubernetes pod with `ulimit -n` set to a large value (e.g. 1e9). Confirm the server starts successfully without hanging at the port check step.
## Does this PR potentially affect the following parts?
- [x] Nope
## Documentation Status
- [x] `Doc - No Need`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3637856705
##########
hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh:
##########
@@ -20,10 +20,10 @@
# TODO: consider reuse it with server-dist module (almost same as it)
function command_available() {
local cmd=$1
- if [ $(command -v $cmd >/dev/null 2>&1) ]; then
- return 1
- else
+ if [[ -x "$(command -v "$cmd")" ]]; then
Review Comment:
⚠️ Correcting `command_available` makes the curl-only `download()` branch reachable, but that branch still uses `-o ${path}/${link_url}`. Its callers pass a full `https://.../opentelemetry-javaagent.jar` URL, so curl tries to write through nonexistent nested `https:/...` directories and telemetry startup still fails when wget is absent; the Store copy has the same behavior. Please fix both helpers to use a basename destination such as `curl -L "$link_url" -o "$path/$(basename "$link_url")"` and cover the curl-only path.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
+ host="127.0.0.1"
+ elif [[ "$host" == "::" ]]; then
+ host="::1"
+ fi
+
+ # Use bash /dev/tcp instead of lsof to avoid the FD-table walk that lsof
+ # performs under inflated nofile limits (e.g. kind / some Kubernetes runtimes),
+ # which pegs CPU and prevents Java from starting.
+ if (echo >/dev/tcp/"$host"/"$port") >/dev/null 2>&1; then
Review Comment:
⚠️ Bash `/dev/tcp` has no deadline here. For a configured local/Pod address whose firewall or CNI drops SYN packets, this check waits for the kernel retry timeout and can still stall startup—the failure mode this change is intended to remove. Please use a probe with an explicit short timeout or inspect listening sockets without initiating a network connection, and cover the timeout path.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
Review Comment:
⚠️ Mapping `0.0.0.0` to `127.0.0.1` only probes loopback. A process listening on another local interface can make the loopback connect fail while the subsequent wildcard Java bind still fails with `EADDRINUSE`; the `::` to `::1` path has the same multi-interface gap. Please make wildcard checks cover the actual bind scope (for example through the kernel listening table or all local addresses) and add IPv4/IPv6 regressions with a non-loopback listener.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
+ host="127.0.0.1"
+ elif [[ "$host" == "::" ]]; then
+ host="::1"
+ fi
+
+ # Use bash /dev/tcp instead of lsof to avoid the FD-table walk that lsof
+ # performs under inflated nofile limits (e.g. kind / some Kubernetes runtimes),
+ # which pegs CPU and prevents Java from starting.
+ if (echo >/dev/tcp/"$host"/"$port") >/dev/null 2>&1; then
Review Comment:
🧹 `echo` writes a newline to whichever service already owns the port, although detecting a listener only requires opening the connection. This can create parse errors, logs, or error metrics in the existing REST/Gremlin service. Please open and close the descriptor without payload, for example with `: >/dev/tcp/"$host"/"$port"`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3650933499
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -286,8 +516,14 @@ function download() {
exit 1
}
fi
- curl -L "${download_url}" -o "${path}/$(basename "${download_url}")"
+ curl -fL "${download_url}" -o "${path}/$(basename "${download_url}")"
Review Comment:
⚠️ This writes curl output directly to the final destination. On a transfer error, curl can leave a partial file there; the telemetry callers then see that path on the next startup, skip the download, and fail checksum validation until an operator deletes it. The PD and Store copies have the same behavior, and the new failure test checks only the return code. Please download to a temporary file in the destination directory and rename only after success (cleaning it on failure), then add a partial-transfer retry regression.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,245 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# Run a command with a hard deadline via background watchdog.
+# Returns the command's exit code if it finishes in time.
+# If the deadline expires, the command is killed (exit code reflects signal).
+# Works without the timeout command — uses sleep + kill -9 pattern.
+function run_with_deadline() {
+ local cmd="$1"
+ local deadline="$2"
+ shift 2
+
+ bash -c "$cmd" bash "$@" &
+ local child_pid=$!
+ (
+ sleep "$deadline"
+ kill -9 "$child_pid" 2>/dev/null
+ ) 2>/dev/null &
+ local watchdog_pid=$!
+
+ wait "$child_pid" 2>/dev/null
+ local rc=$?
+ kill -9 "$watchdog_pid" 2>/dev/null || true
+ wait "$watchdog_pid" 2>/dev/null || true
+ return $rc
+}
+
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme (http://, https://, or none) and path.
+ # This ensures port is extracted from host:port, not from a colon in the path.
+ local authority
+ if [[ "$url" =~ ^[a-zA-Z][a-zA-Z0-9+.-]*:// ]]; then
+ authority=$(echo "$url" | sed 's|^[^/]*://||; s|/.*||')
Review Comment:
⚠️ Authority extraction removes only a `/` suffix, not `?` or `#`. A controlled run with `http://127.0.0.1:8080?probe=x` and `ss` reporting `127.0.0.1:8080` returns success because the authority becomes `127.0.0.1:8080?probe=x`, while Java URI parsing still uses host `127.0.0.1` and port `8080`. Please terminate authority at the first `/`, `?`, or `#` (preferably through one URI-normalization path) and add query/fragment regressions.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,245 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# Run a command with a hard deadline via background watchdog.
+# Returns the command's exit code if it finishes in time.
+# If the deadline expires, the command is killed (exit code reflects signal).
+# Works without the timeout command — uses sleep + kill -9 pattern.
+function run_with_deadline() {
+ local cmd="$1"
+ local deadline="$2"
+ shift 2
+
+ bash -c "$cmd" bash "$@" &
+ local child_pid=$!
+ (
+ sleep "$deadline"
+ kill -9 "$child_pid" 2>/dev/null
+ ) 2>/dev/null &
+ local watchdog_pid=$!
+
+ wait "$child_pid" 2>/dev/null
+ local rc=$?
+ kill -9 "$watchdog_pid" 2>/dev/null || true
+ wait "$watchdog_pid" 2>/dev/null || true
+ return $rc
+}
+
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme (http://, https://, or none) and path.
+ # This ensures port is extracted from host:port, not from a colon in the path.
+ local authority
+ if [[ "$url" =~ ^[a-zA-Z][a-zA-Z0-9+.-]*:// ]]; then
+ authority=$(echo "$url" | sed 's|^[^/]*://||; s|/.*||')
+ else
+ authority=$(echo "$url" | sed 's|/.*||')
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host and port from authority.
+ # Assumes IPv6 is bracketed (e.g. [::1]:8080). Unbracketed IPv6 like
+ # ::1:8080 would misparse as host=::, port=1. ServerOptions does not
+ # enforce bracketing at the config layer; if this ever fires on bad input
+ # the downstream bind would fail with a clearer error than the preflight.
+ if [[ "$authority" =~ ^\[([^\]]*)\]:([0-9]+)$ ]]; then
+ # IPv6 with port: [::1]:8080
+ host="${BASH_REMATCH[1]}"
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" =~ :([0-9]+)$ ]]; then
+ # IPv4 or hostname with port: 127.0.0.1:8080
+ port="${BASH_REMATCH[1]}"
+ host="${authority%:*}"
+ else
+ # No explicit port in authority
+ host="$authority"
+ port=""
+ fi
+
+ # Handle default ports from scheme when no explicit port given
+ if [[ -z "$port" ]]; then
+ # Reject invalid port: authority has exactly one colon (host:non-digits).
+ # IPv6 addresses (2+ colons, e.g. [::1] or ::1) are not caught by this.
+ if [[ "$authority" != *:*:* && "$authority" == *:* ]]; then
+ return 0
+ fi
+ if [[ "$url" == https://* ]]; then
+ port="443"
+ elif [[ "$url" == http://* ]]; then
+ port="80"
+ fi
+ fi
+
+ if [[ -z "$port" ]]; then
+ return 0
+ fi
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Strip any leading/trailing whitespace from host
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ # Resolve hostname → numeric IPs so ss/netstat (which use -n) can match them.
+ # A "hostname" is anything that is not blank, a wildcard, or already numeric.
+ # Resolution runs with a deadline to prevent hangs from slow/stuck DNS/LDAP.
+ # If timeout is unavailable, skip resolution and fall through to bounded /dev/tcp.
+ local resolved_addrs=""
+ local is_hostname=0
+ if [[ -n "$host" && "$host" != "0.0.0.0" && "$host" != "::" && "$host" != "*" ]] \
+ && ! [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
+ && ! [[ "$host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ is_hostname=1
+ if command_available "getent" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 getent hosts "$host" 2>/dev/null | awk '{print $1}')
+ elif command_available "dscacheutil" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 dscacheutil -q host -a name "$host" 2>/dev/null \
+ | awk '/ip_address:/{print $2}')
+ fi
+ # If timeout unavailable or resolution times out, resolved_addrs stays empty
+ # and we fall through to the bounded /dev/tcp probe (2s watchdog) instead.
+ fi
+
+ local linux_pattern
+ local bsd_pattern
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ # Wildcard patterns match any address family (IPv4 or IPv6) on the port
+ # Note: This treats IPv4 and IPv6 wildcard listeners as conflicts, which is conservative
+ # but may be overly strict for dual-stack systems where they can coexist
+ linux_pattern=":${port}([[:space:]]|$)"
+ bsd_pattern="(\.|:)${port}([[:space:]]|$)"
+ else
+ # For hostnames, only use resolved numeric addresses (ss/netstat report numeric).
+ # Keep wildcard matching family-aware to avoid cross-family false conflicts.
+ local addr_alts=""
+ local match_ipv4=0
+ local match_ipv6=0
+ if [[ $is_hostname -eq 1 ]]; then
+ # Hostname: use resolved addresses and infer address family set
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ local esc_addr="${addr//./\\.}"
+ if [[ "$addr" == *":"* ]]; then
+ esc_addr="${esc_addr//:/\\:}"
+ match_ipv6=1
+ else
+ match_ipv4=1
+ fi
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="${esc_addr}|\[${esc_addr}\]"
+ else
+ addr_alts="${addr_alts}|${esc_addr}|\[${esc_addr}\]"
+ fi
+ done <<< "$resolved_addrs"
+ else
+ # Numeric address: use it directly and infer address family
+ local esc_host="${host//./\\.}"
Review Comment:
‼️ Numeric IPv6 addresses are compared as escaped text, so equivalent spellings are treated as different endpoints. On this head, mocked `ss` output for `[::1]:8080` makes `check_port "http://[0:0:0:0:0:0:0:1]:8080"` return success even though both addresses identify the same socket and the later bind fails with `EADDRINUSE`; mixed-case hex has the same problem. Please canonicalize configured and listener-table IPv6 addresses before comparison (or compare parsed binary addresses), and add compressed/expanded and case-variation regressions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3675454508
##########
hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh:
##########
@@ -286,26 +311,37 @@ download_and_verify() {
local url=$1
local filepath=$2
local expected_md5=$3
+ local actual_md5
- if [[ -f $filepath ]]; then
+ if [[ -f "$filepath" ]]; then
echo "File $filepath exists. Verifying MD5 checksum..."
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
+ actual_md5=$(md5sum -- "$filepath" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
echo "MD5 checksum verification failed for $filepath. Expected: $expected_md5, but got: $actual_md5"
echo "Deleting $filepath..."
- rm -f $filepath
+ rm -f -- "$filepath"
Review Comment:
Addressed in `8b4e01ae`. A checksum mismatch no longer removes the shared destination; every caller downloads to its own adjacent `mktemp`, verifies that file, and only then publishes with `mv -f`. The coordinated two-caller regression holds a stale checksum until another caller installs valid bytes, forces the stale caller's download to fail, and asserts the valid destination survives with no temp files. Successful callers publish the same expected checksum, so this contract does not require a new lock dependency.
##########
.github/workflows/docker-build-ci.yml:
##########
@@ -47,6 +47,28 @@ jobs:
run: |
IMAGE_ID=$(docker build -q -f ${{ matrix.dockerfile }} .)
echo "Built: $IMAGE_ID"
+ echo "IMAGE_ID=$IMAGE_ID" >> "$GITHUB_ENV"
HC=$(docker inspect --format='{{json .Config.Healthcheck}}' "$IMAGE_ID")
echo "Healthcheck: $HC"
[[ "$HC" != "null" ]] || { echo "ERROR: HEALTHCHECK missing in ${{ matrix.dockerfile }}"; exit 1; }
+
+ # The startup preflight needs a socket-table tool, and the base image
+ # ships none of its own. Without one every start reports "unknown" and
+ # a duplicate start is no longer refused, so assert the image can
+ # actually answer. Only the server images run check_port.
+ # TODO(docker-ci): this pins the probe dependency, not the behaviour it
+ # protects. A full duplicate-start/stop check needs a booted server with
+ # a backend, which belongs with the e2e job rather than the image build.
+ - name: Port preflight can answer inside ${{ matrix.dockerfile }}
Review Comment:
Addressed in `8b4e01ae`. `pull_request.paths` now includes the exact probed file: `hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh`. The workflow parses successfully and the structural path assertion passes; this push has also triggered Docker Build CI.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,395 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo "SKIP: util.sh not found at $UTIL_SH"
+ exit 0
Review Comment:
Addressed in `8b4e01ae`. An explicitly supplied missing server utility now prints `ERROR` and exits 1; an explicitly supplied missing Store utility does the same. Only no-argument discovery may skip. Both Linux and macOS workflow calls now pass the exact server and Store utility paths, and both negative invocations were verified locally.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -185,16 +366,31 @@ function wait_for_startup() {
return 1
fi
- status=$(curl -I -sS -k -w "%{http_code}" -o /dev/null "$server_url" 2> "$error_file_name")
- if [[ $status -eq 200 || $status -eq 401 ]]; then
+ # Bound each probe by the time left in the overall deadline: without
+ # --max-time a single blackholed request blocks past ${timeout_s}s.
+ local remain_s=$((stop_s - now_s))
+ [ "$remain_s" -lt 1 ] && remain_s=1
Review Comment:
Addressed in `8b4e01ae`. `wait_for_startup` now uses an exclusive loop boundary, refreshes the clock immediately before curl, and stops when `remain_s <= 0` instead of granting a new one-second budget. The file-backed clock regression lands exactly on the deadline and asserts that curl receives zero calls. Current focused suite: 60/60 on macOS Bash 3.2.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3659911379
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,170 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms; Java reads 08080 as decimal 8080.
+ port=$((10#$port))
Review Comment:
⚠️ `parse_port_from_url()` converts the digit string before bounding its size, so Bash integer overflow can turn an invalid configured port into a valid one. On this exact head, `parse_port_from_url "http://127.0.0.1:18446744073709551617"` prints `1` and returns 0 because `$((10#$port))` wraps before the `1..65535` check; the 44-case suite only covers `70000`. Please strip leading zeroes and reject values longer or lexically larger than `65535` before arithmetic conversion, then add an oversized-integer regression.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3650067959
##########
hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh:
##########
@@ -20,10 +20,10 @@
# TODO: consider reuse it with server-dist module (almost same as it)
function command_available() {
local cmd=$1
- if [ $(command -v $cmd >/dev/null 2>&1) ]; then
- return 1
- else
+ if [[ -x "$(command -v "$cmd")" ]]; then
Review Comment:
Resolved: curl download path now uses curl -fL with basename output.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
Review Comment:
Resolved: ss/netstat probes now check actual kernel socket table, not limited to loopback.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
+ host="127.0.0.1"
+ elif [[ "$host" == "::" ]]; then
+ host="::1"
+ fi
+
+ # Use bash /dev/tcp instead of lsof to avoid the FD-table walk that lsof
+ # performs under inflated nofile limits (e.g. kind / some Kubernetes runtimes),
+ # which pegs CPU and prevents Java from starting.
+ if (echo >/dev/tcp/"$host"/"$port") >/dev/null 2>&1; then
Review Comment:
Resolved: /dev/tcp now has timeout 1 (when available) or run_with_deadline() with 2s watchdog.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,36 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
+ host="127.0.0.1"
+ elif [[ "$host" == "::" ]]; then
+ host="::1"
+ fi
+
+ # Use bash /dev/tcp instead of lsof to avoid the FD-table walk that lsof
+ # performs under inflated nofile limits (e.g. kind / some Kubernetes runtimes),
+ # which pegs CPU and prevents Java from starting.
+ if (echo >/dev/tcp/"$host"/"$port") >/dev/null 2>&1; then
Review Comment:
Resolved: uses : (null command) for /dev/tcp probe — no payload sent to services.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3658239383
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -109,27 +110,417 @@ function parse_yaml() {
}
function process_num() {
+ local num
num=$(ps -ef | grep "$1" | grep -v grep | wc -l)
- return "$num"
+ # Return 0 when no process, 1 when one or more. Using $num directly as an
+ # exit code would truncate values > 255, so treat this as a boolean result.
+ if (( num > 0 )); then
+ return 1
+ fi
+ return 0
}
function process_id() {
+ local pid
pid=$(ps -ef | grep "$1" | grep -v grep | awk '{print $2}')
- return "$pid"
+ echo "$pid"
+ return 0
+}
+
+# Run a command with a hard deadline via background watchdog.
+# Returns the command's exit code if it finishes in time.
+# If the deadline expires, the command is killed (exit code reflects signal).
+# Works without the timeout command — uses sleep + kill -9 pattern.
+function run_with_deadline() {
+ local cmd="$1"
+ local deadline="$2"
+ shift 2
+
+ bash -c "$cmd" bash "$@" &
+ local child_pid=$!
+ (
+ local sleep_pid=""
+ cleanup_watchdog() {
+ [[ -n "$sleep_pid" ]] && kill -9 "$sleep_pid" 2>/dev/null
+ }
+ # Kill any direct children of the target PID (e.g. a spawned sleep)
+ # in case killing the wrapper left them orphaned.
+ kill_children() {
+ local child
+ for child in $(pgrep -P "$1" 2>/dev/null); do
+ kill -9 "$child" 2>/dev/null || true
+ done
+ }
+ trap 'cleanup_watchdog' EXIT TERM
+ sleep "$deadline" & sleep_pid=$!
+ wait "$sleep_pid" 2>/dev/null
+ if kill -0 "$child_pid" 2>/dev/null; then
+ kill -9 "$child_pid" 2>/dev/null
+ kill_children "$child_pid"
+ fi
+ ) 2>/dev/null &
+ local watchdog_pid=$!
+
+ wait "$child_pid" 2>/dev/null
+ local rc=$?
+ # Kill the watchdog with SIGTERM so its EXIT trap reaps the sleep child.
+ kill -TERM "$watchdog_pid" 2>/dev/null || true
+ wait "$watchdog_pid" 2>/dev/null || true
+ return $rc
+}
+
+
+# Normalize an IP address to a canonical string for comparison.
+# - IPv4 addresses are returned unchanged.
+# - IPv6 addresses are stripped of brackets/zone scope, lowercased and
+# compressed to the canonical textual form (via getent ahosts).
+# - IPv4-mapped IPv6 (::ffff:1.2.3.4) is collapsed to the IPv4 form.
+# - Hostnames are returned unchanged; callers should resolve them first.
+function normalize_addr() {
+ local addr="$1"
+
+ # Strip brackets
+ if [[ "$addr" =~ ^\[.*\]$ ]]; then
+ addr="${addr#\[}"
+ addr="${addr%\]}"
+ fi
+
+ # Drop IPv6 zone scope (e.g. 127.0.0.53%lo, fe80::1%eth0)
+ addr="${addr%%\%*}"
+
+ # IPv4-mapped IPv6 -> IPv4 so a bound IPv4-mapped socket is compared
+ # against an IPv4-configured address.
+ if [[ "$addr" =~ ^::ffff:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
+ echo "${BASH_REMATCH[1]}"
+ return
+ fi
+
+ # Plain IPv4
+ if [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "$addr"
+ return
+ fi
+
+ # IPv6: ask glibc for the canonical compressed form
+ if [[ "$addr" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ local norm
+ if command_available "timeout"; then
+ norm=$(timeout 2 getent ahosts "$addr" 2>/dev/null | awk '{print $1; exit}')
+ else
+ norm=$(getent ahosts "$addr" 2>/dev/null | awk '{print $1; exit}')
+ fi
+ if [[ -n "$norm" ]]; then
+ echo "$norm"
+ return
+ fi
+ # macOS/BSD fallback: python3's socket module can canonicalise
+ # numeric IPv6 even when getent is unavailable.
+ if command_available "python3"; then
+ norm=$(python3 -c 'import socket, sys; print(socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, sys.argv[1])))' "$addr" 2>/dev/null)
+ if [[ -n "$norm" ]]; then
+ echo "$norm"
+ return
+ fi
+ fi
+ # No canonicaliser available: at least normalise hex case so ss/netstat
+ # lowercase output still matches an uppercase configured address.
+ echo "$addr" | tr '[:upper:]' '[:lower:]'
+ return
+ fi
+
+ # Fall back to the cleaned original
+ echo "$addr"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme and stop at the first /, ? or #.
+ local authority
+ authority="${url#*://}"
+ authority="${authority%%[/?#]*}"
+
+ # Extract host and port from authority.
+ if [[ "$authority" =~ ^\[([^\]]*)\]:([0-9]+)$ ]]; then
+ # IPv6 with port: [::1]:8080
+ host="${BASH_REMATCH[1]}"
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" =~ ^\[([^\]]*)\]$ ]]; then
+ # IPv6 without port: [::1]
+ host="${BASH_REMATCH[1]}"
+ port=""
+ elif [[ "$authority" =~ :([0-9]+)$ ]]; then
+ # IPv4 or hostname with port: 127.0.0.1:8080, localhost:8080
+ port="${BASH_REMATCH[1]}"
+ host="${authority%:*}"
+ else
+ # No explicit port in authority
+ host="$authority"
+ port=""
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Handle default ports from scheme when no explicit port is given
+ if [[ -z "$port" ]]; then
+ if [[ "$url" == https://* ]]; then
+ port="443"
+ elif [[ "$url" == http://* ]]; then
+ port="80"
+ else
+ return 0
+ fi
+ fi
+
+ # Validate port as a decimal number
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Strip any leading/trailing whitespace from host
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ local norm_host
+ norm_host=$(normalize_addr "$host")
+
+ # Determine the address family of the configured host so we only treat
+ # same-family wildcard listeners as conflicts (IPv4 vs IPv6 sockets are
+ # separate unless explicitly dual-stacked).
+ local host_family=""
+ if [[ "$norm_host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ host_family="ipv4"
+ elif [[ "$norm_host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ host_family="ipv6"
+ else
+ host_family="hostname"
+ fi
+
+ local in_use=0
+ local port_checked=0
+
+ # Wildcard binds are detected by looking for any listener on the port.
+ # Specific hosts are matched against the local address; if the listener
+ # is a same-family wildcard (0.0.0.0 / :: / *), that is a conflict too.
+ local is_wildcard=0
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ is_wildcard=1
+ fi
+
+ # Build the list of acceptable normalized addresses for a specific host.
+ # Hostnames must be resolved to numeric IPs first because ss/netstat
+ # output is always numeric.
+ local candidate_addrs=""
+ if [[ $is_wildcard -eq 0 ]]; then
+ if [[ "$host_family" == "ipv4" || "$host_family" == "ipv6" ]]; then
+ # Already numeric
+ candidate_addrs="$norm_host"
+ else
+ # Hostname: resolve with deadline
+ if command_available "getent" && command_available "timeout"; then
+ candidate_addrs=$(timeout 2 getent ahosts "$host" 2>/dev/null | awk '{print $1}')
+ elif command_available "dscacheutil" && command_available "timeout"; then
+ candidate_addrs=$(timeout 2 dscacheutil -q host -a name "$host" 2>/dev/null \
+ | awk '/ip_address:/{print $2}')
+ fi
+ fi
+ fi
+
+ # Helper: scan a line of listener-table output and return 0 if it matches
+ # the configured host/port. Sets 'matched_token' to 1 when it evaluates a
+ # token that we can trust, so callers know whether "no match" is reliable.
+ local out line listener_addr norm_listener token matched_token
+
+ # Returns true if the listener address is a wildcard on the same family
+ # as the configured host (or any family, if the host is a wildcard).
+ _check_port_wildcard_conflicts() {
+ local wl_addr="$1"
+ if [[ $is_wildcard -eq 1 ]]; then
+ return 0
+ fi
+ # BSD netstat prints *.<port> for an any-family wildcard.
+ if [[ "$wl_addr" == "*" ]]; then
+ return 0
+ fi
+ if [[ "$wl_addr" == "0.0.0.0" ]]; then
+ [[ "$host_family" == "ipv4" ]] && return 0
+ # A hostname that resolved to IPv4 can also bind an IPv4 wildcard
+ if [[ "$host_family" == "hostname" ]]; then
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ fi
+ fi
+ if [[ "$wl_addr" == "::" ]]; then
+ [[ "$host_family" == "ipv6" ]] && return 0
+ if [[ "$host_family" == "hostname" ]]; then
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$addr" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ fi
+ fi
+ return 1
+ }
+
+ _check_port_match_listener_line() {
+ local out_line="$1"
+ # Skip empty or whitespace-only lines before read -a to avoid an empty
+ # array expansion under set -u on Bash 3.2.
+ if [[ -z "${out_line//[[:space:]]/}" ]]; then
+ return 1
+ fi
+ local -a tokens
+ read -r -a tokens <<< "$out_line"
+ for token in ${tokens[@]+"${tokens[@]}"}; do
+ # We only care about the "local address:port" token. For the
+ # common tools this is the first token that ends with the
+ # target port after ':' or '.' (peer addresses use :* on Linux
+ # and *.* on BSD, so they never match a numeric port).
+ if [[ "$token" =~ ^(.*):(${port})$ ]]; then
+ listener_addr="${BASH_REMATCH[1]}"
+ elif [[ "$token" =~ ^(.*)\.(${port})$ ]]; then
+ listener_addr="${BASH_REMATCH[1]}"
+ else
+ continue
+ fi
+
+ # Wildcard host: any listener on this port is a conflict.
+ if [[ $is_wildcard -eq 1 ]]; then
+ matched_token=1
+ return 0
+ fi
+
+ # No resolved candidates (hostname resolution failed/unsupported):
+ # we cannot reliably compare against the numeric listener table.
+ if [[ -z "$candidate_addrs" ]]; then
+ continue
+ fi
+
+ matched_token=1
+ norm_listener=$(normalize_addr "$listener_addr")
+
+ # A same-family wildcard listener on this port conflicts with any
+ # specific host of that family.
+ if _check_port_wildcard_conflicts "$norm_listener"; then
+ return 0
+ fi
+
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$norm_listener" == "$(normalize_addr "$addr")" ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ done
+ return 1
+ }
+
+ if command_available "ss"; then
+ matched_token=0
+ if out=$(ss -ltn 2>/dev/null); then
+ while IFS= read -r line; do
+ if _check_port_match_listener_line "$line"; then
+ in_use=1
+ break
+ fi
+ done <<< "$out"
+ # ss -ltn succeeded. We can trust a non-match when we have a
+ # numeric host or resolved addresses (or a wildcard); otherwise
+ # fall through to /dev/tcp for unresolved hostnames.
+ if [[ $in_use -eq 0 && ( $is_wildcard -eq 1 || -n "$candidate_addrs" || $matched_token -eq 1 ) ]]; then
+ port_checked=1
+ fi
+ fi
+ fi
+
+ if [[ $in_use -eq 0 && $port_checked -eq 0 ]] && command_available "netstat"; then
+ matched_token=0
+ if out=$(netstat -ltn 2>/dev/null) && echo "$out" | grep -qi "listen"; then
Review Comment:
Fixed in `5f4a70d1`.
The parser no longer scans every token in every row. Detection is now OS-selected and inspects only `LISTEN` rows and only the local-address column:
- macOS/BSD: `netstat -an -p tcp`, rows filtered on `$NF == "LISTEN"`
- Linux: `ss -H -ltn` (already listen-only), falling back to `netstat -ltn`
The address is split on its **last** separator, so an IPv6 hextet such as `[2001:db8:8080::1]:9090` can no longer be read as port 8080.
Reproduced your case on macOS before and after. With 37 `ESTABLISHED` connections to `:443` and `netstat -an -p tcp | awk '$NF=="LISTEN" && $4 ~ /\.443$/'` empty:
```
before: check_port "http://0.0.0.0:443" -> "The port 443 has already been used", exit 1
after : check_port "http://0.0.0.0:443" -> exit 0 (free)
```
Per your note that a conservative port-only comparison is sufficient, I also took the rest of the minimal design: DNS resolution, address canonicalization, cross-family matching, `/dev/tcp` and its watchdog are removed, and the result is now `busy` / `free` / `unknown`.
Two regressions in the suite cover this specifically: a `TIME_WAIT` row whose **local** port is the target must read `free`, and a row where only the **foreign** address carries the port must read `free`. Both fail if the `LISTEN` filter or the column restriction is removed — I verified that by mutation rather than assuming.
##########
hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh:
##########
@@ -286,26 +313,33 @@ download_and_verify() {
local url=$1
local filepath=$2
local expected_md5=$3
+ local actual_md5
- if [[ -f $filepath ]]; then
+ if [[ -f "$filepath" ]]; then
echo "File $filepath exists. Verifying MD5 checksum..."
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
+ actual_md5=$(md5sum -- "$filepath" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
echo "MD5 checksum verification failed for $filepath. Expected: $expected_md5, but got: $actual_md5"
echo "Deleting $filepath..."
- rm -f $filepath
+ rm -f -- "$filepath"
else
echo "MD5 checksum verification succeeded for $filepath."
return 0
fi
fi
echo "Downloading $filepath..."
- curl -L -o $filepath $url
-
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
- echo "MD5 checksum verification failed for $filepath after download. Expected: $expected_md5, but got: $actual_md5"
+ local tmp="${filepath}.tmp.$$"
+ if curl -fL -o "$tmp" -- "$url"; then
+ actual_md5=$(md5sum -- "$tmp" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
+ echo "MD5 checksum verification failed for $filepath after download. Expected: $expected_md5, but got: $actual_md5"
+ rm -f -- "$tmp"
+ return 1
+ fi
+ mv -f -- "$tmp" "$filepath"
Review Comment:
Fixed in `5f4a70d1`, using your suggestion as written:
```bash
mv -f -- "$tmp" "$filepath" || { rm -f -- "$tmp"; return 1; }
```
The unconditional `return 0` is gone, so a failed rename can no longer make callers export `LD_PRELOAD` for a library that never installed.
The same bug was present in `download()` in all three copies (server, PD, store) — the rename there was also unchecked — so it is fixed in each.
Covered by a rename-failure test that stubs `mv` to fail and asserts three things: `download` returns non-zero, no destination file is left behind, and the temp file is cleaned up.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin merged PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3645160690
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,65 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]] || (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ local in_use=0
+ if command_available "ss"; then
+ if ss -ltn 2>/dev/null | grep -qE "(:${port}\b|:${port}$)"; then
Review Comment:
⚠️ The primary probes do not identify the configured local endpoint: they match every listener by port, and the `ss` expression can even match the target digits inside an IPv6 address (for example, `[2001:db8:8080::1]:9090` matches a check for port 8080). A listener on another specific interface can therefore reject a valid bind, while an IPv6 hextet can produce the same false positive. Please parse the local-address field and compare the configured host/port with wildcard and dual-stack conflict semantics, then add distinct-address and IPv6-hextet regressions.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,65 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]] || (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ local in_use=0
+ if command_available "ss"; then
Review Comment:
⚠️ Tool presence is treated as a successful probe. If an installed `ss` exits nonzero, this branch neither distinguishes that failure from an empty listener table nor tries `netstat` or `/dev/tcp`; the same silent-free result occurs when both `netstat` invocations fail. Please capture each probe's execution status, advance to the next layer on failure, and add cases where a present tool returns nonzero.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-start-hugegraph-pd.sh:
##########
@@ -72,9 +72,9 @@ cleanup() {
fi
rm -f "$PID_FILE"
rm -rf "$PD_ROOT/logs/"
- # kill anything still holding the PD port
- lsof -ti :8620 | xargs kill -9 2>/dev/null || true
- lsof -ti :8686 | xargs kill -9 2>/dev/null || true
+ # kill anything still holding the PD port (fuser avoids lsof dependency)
+ fuser -k 8620/tcp 2>/dev/null || true
Review Comment:
⚠️ This cleanup now depends on `fuser`, but the PD workflow preflight still requires `lsof curl java` and never checks `fuser`. An lsof-free environment therefore skips the revised suite, while a runner without `fuser` executes it with silently ineffective port cleanup. Please remove the obsolete `lsof` gate, require `fuser` (or make cleanup dependency-free), and fail explicitly when cleanup cannot release the test ports.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3652292358
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -109,27 +110,417 @@ function parse_yaml() {
}
function process_num() {
+ local num
num=$(ps -ef | grep "$1" | grep -v grep | wc -l)
- return "$num"
+ # Return 0 when no process, 1 when one or more. Using $num directly as an
+ # exit code would truncate values > 255, so treat this as a boolean result.
+ if (( num > 0 )); then
+ return 1
+ fi
+ return 0
}
function process_id() {
+ local pid
pid=$(ps -ef | grep "$1" | grep -v grep | awk '{print $2}')
- return "$pid"
+ echo "$pid"
+ return 0
+}
+
+# Run a command with a hard deadline via background watchdog.
+# Returns the command's exit code if it finishes in time.
+# If the deadline expires, the command is killed (exit code reflects signal).
+# Works without the timeout command — uses sleep + kill -9 pattern.
+function run_with_deadline() {
+ local cmd="$1"
+ local deadline="$2"
+ shift 2
+
+ bash -c "$cmd" bash "$@" &
+ local child_pid=$!
+ (
+ local sleep_pid=""
+ cleanup_watchdog() {
+ [[ -n "$sleep_pid" ]] && kill -9 "$sleep_pid" 2>/dev/null
+ }
+ # Kill any direct children of the target PID (e.g. a spawned sleep)
+ # in case killing the wrapper left them orphaned.
+ kill_children() {
+ local child
+ for child in $(pgrep -P "$1" 2>/dev/null); do
+ kill -9 "$child" 2>/dev/null || true
+ done
+ }
+ trap 'cleanup_watchdog' EXIT TERM
+ sleep "$deadline" & sleep_pid=$!
+ wait "$sleep_pid" 2>/dev/null
+ if kill -0 "$child_pid" 2>/dev/null; then
+ kill -9 "$child_pid" 2>/dev/null
+ kill_children "$child_pid"
+ fi
+ ) 2>/dev/null &
+ local watchdog_pid=$!
+
+ wait "$child_pid" 2>/dev/null
+ local rc=$?
+ # Kill the watchdog with SIGTERM so its EXIT trap reaps the sleep child.
+ kill -TERM "$watchdog_pid" 2>/dev/null || true
+ wait "$watchdog_pid" 2>/dev/null || true
+ return $rc
+}
+
+
+# Normalize an IP address to a canonical string for comparison.
+# - IPv4 addresses are returned unchanged.
+# - IPv6 addresses are stripped of brackets/zone scope, lowercased and
+# compressed to the canonical textual form (via getent ahosts).
+# - IPv4-mapped IPv6 (::ffff:1.2.3.4) is collapsed to the IPv4 form.
+# - Hostnames are returned unchanged; callers should resolve them first.
+function normalize_addr() {
+ local addr="$1"
+
+ # Strip brackets
+ if [[ "$addr" =~ ^\[.*\]$ ]]; then
+ addr="${addr#\[}"
+ addr="${addr%\]}"
+ fi
+
+ # Drop IPv6 zone scope (e.g. 127.0.0.53%lo, fe80::1%eth0)
+ addr="${addr%%\%*}"
+
+ # IPv4-mapped IPv6 -> IPv4 so a bound IPv4-mapped socket is compared
+ # against an IPv4-configured address.
+ if [[ "$addr" =~ ^::ffff:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
+ echo "${BASH_REMATCH[1]}"
+ return
+ fi
+
+ # Plain IPv4
+ if [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "$addr"
+ return
+ fi
+
+ # IPv6: ask glibc for the canonical compressed form
+ if [[ "$addr" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ local norm
+ if command_available "timeout"; then
+ norm=$(timeout 2 getent ahosts "$addr" 2>/dev/null | awk '{print $1; exit}')
+ else
+ norm=$(getent ahosts "$addr" 2>/dev/null | awk '{print $1; exit}')
+ fi
+ if [[ -n "$norm" ]]; then
+ echo "$norm"
+ return
+ fi
+ # macOS/BSD fallback: python3's socket module can canonicalise
+ # numeric IPv6 even when getent is unavailable.
+ if command_available "python3"; then
+ norm=$(python3 -c 'import socket, sys; print(socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, sys.argv[1])))' "$addr" 2>/dev/null)
+ if [[ -n "$norm" ]]; then
+ echo "$norm"
+ return
+ fi
+ fi
+ # No canonicaliser available: at least normalise hex case so ss/netstat
+ # lowercase output still matches an uppercase configured address.
+ echo "$addr" | tr '[:upper:]' '[:lower:]'
+ return
+ fi
+
+ # Fall back to the cleaned original
+ echo "$addr"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme and stop at the first /, ? or #.
+ local authority
+ authority="${url#*://}"
+ authority="${authority%%[/?#]*}"
+
+ # Extract host and port from authority.
+ if [[ "$authority" =~ ^\[([^\]]*)\]:([0-9]+)$ ]]; then
+ # IPv6 with port: [::1]:8080
+ host="${BASH_REMATCH[1]}"
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" =~ ^\[([^\]]*)\]$ ]]; then
+ # IPv6 without port: [::1]
+ host="${BASH_REMATCH[1]}"
+ port=""
+ elif [[ "$authority" =~ :([0-9]+)$ ]]; then
+ # IPv4 or hostname with port: 127.0.0.1:8080, localhost:8080
+ port="${BASH_REMATCH[1]}"
+ host="${authority%:*}"
+ else
+ # No explicit port in authority
+ host="$authority"
+ port=""
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Handle default ports from scheme when no explicit port is given
+ if [[ -z "$port" ]]; then
+ if [[ "$url" == https://* ]]; then
+ port="443"
+ elif [[ "$url" == http://* ]]; then
+ port="80"
+ else
+ return 0
+ fi
+ fi
+
+ # Validate port as a decimal number
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Strip any leading/trailing whitespace from host
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ local norm_host
+ norm_host=$(normalize_addr "$host")
+
+ # Determine the address family of the configured host so we only treat
+ # same-family wildcard listeners as conflicts (IPv4 vs IPv6 sockets are
+ # separate unless explicitly dual-stacked).
+ local host_family=""
+ if [[ "$norm_host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ host_family="ipv4"
+ elif [[ "$norm_host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ host_family="ipv6"
+ else
+ host_family="hostname"
+ fi
+
+ local in_use=0
+ local port_checked=0
+
+ # Wildcard binds are detected by looking for any listener on the port.
+ # Specific hosts are matched against the local address; if the listener
+ # is a same-family wildcard (0.0.0.0 / :: / *), that is a conflict too.
+ local is_wildcard=0
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ is_wildcard=1
+ fi
+
+ # Build the list of acceptable normalized addresses for a specific host.
+ # Hostnames must be resolved to numeric IPs first because ss/netstat
+ # output is always numeric.
+ local candidate_addrs=""
+ if [[ $is_wildcard -eq 0 ]]; then
+ if [[ "$host_family" == "ipv4" || "$host_family" == "ipv6" ]]; then
+ # Already numeric
+ candidate_addrs="$norm_host"
+ else
+ # Hostname: resolve with deadline
+ if command_available "getent" && command_available "timeout"; then
+ candidate_addrs=$(timeout 2 getent ahosts "$host" 2>/dev/null | awk '{print $1}')
+ elif command_available "dscacheutil" && command_available "timeout"; then
+ candidate_addrs=$(timeout 2 dscacheutil -q host -a name "$host" 2>/dev/null \
+ | awk '/ip_address:/{print $2}')
+ fi
+ fi
+ fi
+
+ # Helper: scan a line of listener-table output and return 0 if it matches
+ # the configured host/port. Sets 'matched_token' to 1 when it evaluates a
+ # token that we can trust, so callers know whether "no match" is reliable.
+ local out line listener_addr norm_listener token matched_token
+
+ # Returns true if the listener address is a wildcard on the same family
+ # as the configured host (or any family, if the host is a wildcard).
+ _check_port_wildcard_conflicts() {
+ local wl_addr="$1"
+ if [[ $is_wildcard -eq 1 ]]; then
+ return 0
+ fi
+ # BSD netstat prints *.<port> for an any-family wildcard.
+ if [[ "$wl_addr" == "*" ]]; then
+ return 0
+ fi
+ if [[ "$wl_addr" == "0.0.0.0" ]]; then
+ [[ "$host_family" == "ipv4" ]] && return 0
+ # A hostname that resolved to IPv4 can also bind an IPv4 wildcard
+ if [[ "$host_family" == "hostname" ]]; then
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$addr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ fi
+ fi
+ if [[ "$wl_addr" == "::" ]]; then
+ [[ "$host_family" == "ipv6" ]] && return 0
+ if [[ "$host_family" == "hostname" ]]; then
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$addr" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ fi
+ fi
+ return 1
+ }
+
+ _check_port_match_listener_line() {
+ local out_line="$1"
+ # Skip empty or whitespace-only lines before read -a to avoid an empty
+ # array expansion under set -u on Bash 3.2.
+ if [[ -z "${out_line//[[:space:]]/}" ]]; then
+ return 1
+ fi
+ local -a tokens
+ read -r -a tokens <<< "$out_line"
+ for token in ${tokens[@]+"${tokens[@]}"}; do
+ # We only care about the "local address:port" token. For the
+ # common tools this is the first token that ends with the
+ # target port after ':' or '.' (peer addresses use :* on Linux
+ # and *.* on BSD, so they never match a numeric port).
+ if [[ "$token" =~ ^(.*):(${port})$ ]]; then
+ listener_addr="${BASH_REMATCH[1]}"
+ elif [[ "$token" =~ ^(.*)\.(${port})$ ]]; then
+ listener_addr="${BASH_REMATCH[1]}"
+ else
+ continue
+ fi
+
+ # Wildcard host: any listener on this port is a conflict.
+ if [[ $is_wildcard -eq 1 ]]; then
+ matched_token=1
+ return 0
+ fi
+
+ # No resolved candidates (hostname resolution failed/unsupported):
+ # we cannot reliably compare against the numeric listener table.
+ if [[ -z "$candidate_addrs" ]]; then
+ continue
+ fi
+
+ matched_token=1
+ norm_listener=$(normalize_addr "$listener_addr")
+
+ # A same-family wildcard listener on this port conflicts with any
+ # specific host of that family.
+ if _check_port_wildcard_conflicts "$norm_listener"; then
+ return 0
+ fi
+
+ local addr
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ if [[ "$norm_listener" == "$(normalize_addr "$addr")" ]]; then
+ return 0
+ fi
+ done <<< "$candidate_addrs"
+ done
+ return 1
+ }
+
+ if command_available "ss"; then
+ matched_token=0
+ if out=$(ss -ltn 2>/dev/null); then
+ while IFS= read -r line; do
+ if _check_port_match_listener_line "$line"; then
+ in_use=1
+ break
+ fi
+ done <<< "$out"
+ # ss -ltn succeeded. We can trust a non-match when we have a
+ # numeric host or resolved addresses (or a wildcard); otherwise
+ # fall through to /dev/tcp for unresolved hostnames.
+ if [[ $in_use -eq 0 && ( $is_wildcard -eq 1 || -n "$candidate_addrs" || $matched_token -eq 1 ) ]]; then
+ port_checked=1
+ fi
+ fi
+ fi
+
+ if [[ $in_use -eq 0 && $port_checked -eq 0 ]] && command_available "netstat"; then
+ matched_token=0
+ if out=$(netstat -ltn 2>/dev/null) && echo "$out" | grep -qi "listen"; then
Review Comment:
‼️ On macOS, `netstat -ltn` succeeds but includes non-listening TCP states. This branch only checks whether the complete output contains any `LISTEN`, then scans every token in every row, so an unrelated `ESTABLISHED` peer port can be mistaken for a local listener. I reproduced this on macOS: no listener existed on 443 (`lsof -iTCP:443 -sTCP:LISTEN` was empty), but an outbound connection to `:443` made `check_port "http://0.0.0.0:443"` exit 1. Please select the parser by OS and inspect only the local-address field of `LISTEN` rows; a conservative port-only comparison is sufficient here.
##########
hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh:
##########
@@ -286,26 +313,33 @@ download_and_verify() {
local url=$1
local filepath=$2
local expected_md5=$3
+ local actual_md5
- if [[ -f $filepath ]]; then
+ if [[ -f "$filepath" ]]; then
echo "File $filepath exists. Verifying MD5 checksum..."
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
+ actual_md5=$(md5sum -- "$filepath" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
echo "MD5 checksum verification failed for $filepath. Expected: $expected_md5, but got: $actual_md5"
echo "Deleting $filepath..."
- rm -f $filepath
+ rm -f -- "$filepath"
else
echo "MD5 checksum verification succeeded for $filepath."
return 0
fi
fi
echo "Downloading $filepath..."
- curl -L -o $filepath $url
-
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
- echo "MD5 checksum verification failed for $filepath after download. Expected: $expected_md5, but got: $actual_md5"
+ local tmp="${filepath}.tmp.$$"
+ if curl -fL -o "$tmp" -- "$url"; then
+ actual_md5=$(md5sum -- "$tmp" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
+ echo "MD5 checksum verification failed for $filepath after download. Expected: $expected_md5, but got: $actual_md5"
+ rm -f -- "$tmp"
+ return 1
+ fi
+ mv -f -- "$tmp" "$filepath"
Review Comment:
⚠️ A failed atomic rename is overwritten by the unconditional `return 0` below, so callers can export `LD_PRELOAD` as if the verified library were installed even when `mv` failed. Keep this simple: `mv -f -- "$tmp" "$filepath" || { rm -f -- "$tmp"; return 1; }`, and add one rename-failure test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3677413314
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,566 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+STORE_UTIL_SH="${2:-}"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ if [[ $# -gt 0 ]]; then
+ echo "ERROR: required util.sh not found at $UTIL_SH" >&2
+ exit 1
+ fi
+ # With no argument this script may be discovered outside the repository by
+ # an optional test runner. CI always supplies STATIC_DIR explicitly, so a
+ # bad workflow path takes the required failure branch above.
+ echo "SKIP: default util.sh not found at $UTIL_SH"
+ exit 0
+fi
+
+if [[ -n "$STORE_UTIL_SH" && ! -f "$STORE_UTIL_SH" ]]; then
+ echo "ERROR: required Store util.sh not found at $STORE_UTIL_SH" >&2
+ exit 1
+fi
+
+# shellcheck source=/dev/null
+source "$UTIL_SH"
+
+# Sections run in subshells so their command overrides stay isolated, which
+# means results have to be tallied through a file rather than a variable.
+RESULTS=$(mktemp)
+# Clean the tally on any exit, not only the normal one. Section 5 runs outside
+# a subshell and has to extend this trap, so it restores this handler rather
+# than clearing it.
+trap 'rm -f "$RESULTS"' EXIT
+
+pass() {
+ echo " PASS $1"
+ echo "P" >> "$RESULTS"
+}
+
+fail() {
+ echo " FAIL $1"
+ echo " $2"
+ echo "F" >> "$RESULTS"
+}
+
+expect() {
+ # expect <name> <expected> <actual>
+ if [[ "$2" == "$3" ]]; then
+ pass "$1"
+ else
+ fail "$1" "expected '$2', got '$3'"
+ fi
+}
+
+echo ""
+echo "check_port contract tests ($UTIL_SH)"
+
+# --------------------------------------------------------------------------
+echo ""
+echo "1. URL to port"
+# "<url>|<expected>", where SKIP means "no usable port, preflight is skipped".
+url_cases=(
+ 'http://127.0.0.1:8080|8080'
+ 'HTTP://127.0.0.1:8080|8080'
+ 'http://127.0.0.1|80'
+ 'https://127.0.0.1|443'
+ '127.0.0.1:8080|8080'
+ 'http://127.0.0.1:8080/path:9090|8080'
+ 'http://127.0.0.1:8080?probe=x|8080'
+ 'http://127.0.0.1:8080#frag|8080'
+ 'http://user:pass@127.0.0.1:8080|8080'
+ 'http://user@127.0.0.1:8080|8080'
+ 'http://[::1]:8080|8080'
+ 'http://user:pass@[::1]:8080|8080'
+ '[::1]:8080|8080'
+ 'https://[::1]|443'
+ 'http://127.0.0.1:08080|8080'
+ '::1:8080|SKIP'
+ 'http://127.0.0.1:abc|SKIP'
+ 'http://127.0.0.1:0|SKIP'
+ 'http://127.0.0.1:70000|SKIP'
+ '127.0.0.1|SKIP'
+ # Oversized values must be rejected on their digits, not after a 64-bit
+ # arithmetic conversion that would wrap them back into range.
+ 'http://127.0.0.1:18446744073709551617|SKIP'
+ 'http://127.0.0.1:18446744073709559616|SKIP'
+ 'http://127.0.0.1:0000000000000008080|8080'
+ 'http://127.0.0.1:00000|SKIP'
+)
+for case in "${url_cases[@]}"; do
+ url="${case%|*}"
+ want="${case##*|}"
+ got=$(parse_port_from_url " $url " 2>/dev/null) || got="SKIP"
+ expect "$url" "$want" "$got"
+done
+
+# --------------------------------------------------------------------------
+echo ""
+echo "2. Linux: ss busy / free / failure, and the netstat fallback"
+(
+ uname() { echo "Linux"; }
+ command_available() { [[ "$1" == "ss" ]]; }
+ SS_OUT=""
+ SS_RC=0
+ ss() { printf '%s' "$SS_OUT"; return "$SS_RC"; }
Review Comment:
Fixed in `ee8f5559`. The `ss` mock now records argv and rejects anything except exactly `-H -ltn`; the Linux regression models an `ESTAB` row whose local ephemeral port is 8080 and verifies it remains `free` only when the listener filter is present. The focused suite is 62/62 on macOS Bash 3.2. Mutation proof: replacing production `ss -H -ltn` with `ss -H -tn` previously left the suite at 60/60, but now fails 7 assertions, including the exact-argv and non-LISTEN cases. Two fresh independent post-fix full-diff reviews found no actionable issue.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,566 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+STORE_UTIL_SH="${2:-}"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ if [[ $# -gt 0 ]]; then
+ echo "ERROR: required util.sh not found at $UTIL_SH" >&2
+ exit 1
+ fi
+ # With no argument this script may be discovered outside the repository by
+ # an optional test runner. CI always supplies STATIC_DIR explicitly, so a
+ # bad workflow path takes the required failure branch above.
+ echo "SKIP: default util.sh not found at $UTIL_SH"
+ exit 0
+fi
+
+if [[ -n "$STORE_UTIL_SH" && ! -f "$STORE_UTIL_SH" ]]; then
+ echo "ERROR: required Store util.sh not found at $STORE_UTIL_SH" >&2
+ exit 1
+fi
+
+# shellcheck source=/dev/null
+source "$UTIL_SH"
+
+# Sections run in subshells so their command overrides stay isolated, which
+# means results have to be tallied through a file rather than a variable.
+RESULTS=$(mktemp)
+# Clean the tally on any exit, not only the normal one. Section 5 runs outside
+# a subshell and has to extend this trap, so it restores this handler rather
+# than clearing it.
+trap 'rm -f "$RESULTS"' EXIT
+
+pass() {
+ echo " PASS $1"
+ echo "P" >> "$RESULTS"
+}
+
+fail() {
+ echo " FAIL $1"
+ echo " $2"
+ echo "F" >> "$RESULTS"
+}
+
+expect() {
+ # expect <name> <expected> <actual>
+ if [[ "$2" == "$3" ]]; then
+ pass "$1"
+ else
+ fail "$1" "expected '$2', got '$3'"
+ fi
+}
+
+echo ""
+echo "check_port contract tests ($UTIL_SH)"
+
+# --------------------------------------------------------------------------
+echo ""
+echo "1. URL to port"
+# "<url>|<expected>", where SKIP means "no usable port, preflight is skipped".
+url_cases=(
+ 'http://127.0.0.1:8080|8080'
+ 'HTTP://127.0.0.1:8080|8080'
+ 'http://127.0.0.1|80'
+ 'https://127.0.0.1|443'
+ '127.0.0.1:8080|8080'
+ 'http://127.0.0.1:8080/path:9090|8080'
+ 'http://127.0.0.1:8080?probe=x|8080'
+ 'http://127.0.0.1:8080#frag|8080'
+ 'http://user:pass@127.0.0.1:8080|8080'
+ 'http://user@127.0.0.1:8080|8080'
+ 'http://[::1]:8080|8080'
+ 'http://user:pass@[::1]:8080|8080'
+ '[::1]:8080|8080'
+ 'https://[::1]|443'
+ 'http://127.0.0.1:08080|8080'
+ '::1:8080|SKIP'
+ 'http://127.0.0.1:abc|SKIP'
+ 'http://127.0.0.1:0|SKIP'
+ 'http://127.0.0.1:70000|SKIP'
+ '127.0.0.1|SKIP'
+ # Oversized values must be rejected on their digits, not after a 64-bit
+ # arithmetic conversion that would wrap them back into range.
+ 'http://127.0.0.1:18446744073709551617|SKIP'
+ 'http://127.0.0.1:18446744073709559616|SKIP'
+ 'http://127.0.0.1:0000000000000008080|8080'
+ 'http://127.0.0.1:00000|SKIP'
+)
+for case in "${url_cases[@]}"; do
+ url="${case%|*}"
+ want="${case##*|}"
+ got=$(parse_port_from_url " $url " 2>/dev/null) || got="SKIP"
+ expect "$url" "$want" "$got"
+done
+
+# --------------------------------------------------------------------------
+echo ""
+echo "2. Linux: ss busy / free / failure, and the netstat fallback"
+(
+ uname() { echo "Linux"; }
+ command_available() { [[ "$1" == "ss" ]]; }
+ SS_OUT=""
+ SS_RC=0
+ ss() { printf '%s' "$SS_OUT"; return "$SS_RC"; }
+
+ SS_OUT='LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:*'
+ expect "listener on 8080 is busy" "busy" "$(port_listen_state 8080)"
+
+ SS_OUT='LISTEN 0 4096 0.0.0.0:22 0.0.0.0:*'
+ expect "no listener on 8080 is free" "free" "$(port_listen_state 8080)"
+
+ # The port must come from the local-address field, not an IPv6 hextet.
+ SS_OUT='LISTEN 0 128 [2001:db8:8080::1]:9090 [::]:*'
+ expect "IPv6 hextet 8080 is not the port" "free" "$(port_listen_state 8080)"
+
+ SS_OUT='LISTEN 0 128 [::]:8080 [::]:*'
+ expect "IPv6 wildcard listener is busy" "busy" "$(port_listen_state 8080)"
+
+ # A tool that runs but fails proves nothing.
+ SS_OUT=''
+ SS_RC=1
+ expect "ss failure is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # `-H` prints no header, so a zero exit with no output is a positive "this
+ # host has no TCP listeners" - the state a fresh container starts in.
+ SS_RC=0
+ SS_OUT=''
+ expect "ss empty output is free" "free" "$(port_listen_state 8080)"
+
+ # Success with an unusable table proves nothing.
+ SS_OUT='some diagnostic banner'
+ expect "ss unparseable output is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # ...and it must not end the search either: netstat may still have a
+ # readable table. Returning on the first probe left the port "unknown"
+ # even when the fallback could have answered.
+ command_available() { [[ "$1" == "ss" || "$1" == "netstat" ]]; }
+ netstat() {
+ echo 'Active Internet connections (only servers)'
+ echo 'Proto Recv-Q Send-Q Local Address Foreign Address State'
+ echo 'tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN'
+ }
+
+ SS_OUT='some diagnostic banner'
+ expect "unparseable ss falls back to netstat" "busy" "$(port_listen_state 8080)"
+ expect "netstat fallback can also report free" "free" "$(port_listen_state 9999)"
+
+ SS_RC=1
+ SS_OUT=''
+ expect "failed ss falls back to netstat" "busy" "$(port_listen_state 8080)"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "3. macOS/BSD: LISTEN versus ESTABLISHED"
+(
+ uname() { echo "Darwin"; }
+ command_available() { [[ "$1" == "netstat" ]]; }
+ NS_OUT=""
+ netstat() { printf '%s' "$NS_OUT"; }
+
+ NS_OUT='Active Internet connections (including servers)
+Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 *.8080 *.* LISTEN'
+ expect "BSD LISTEN on 8080 is busy" "busy" "$(port_listen_state 8080)"
+
+ # An outbound connection to :443 is not a local listener on 443. This is
+ # the false positive that blocked startup on macOS.
+ NS_OUT='Active Internet connections (including servers)
+Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 192.168.1.3.60320 44.195.16.138.443 ESTABLISHED
+tcp4 0 0 *.22 *.* LISTEN'
+ expect "BSD ESTABLISHED peer :443 is free" "free" "$(port_listen_state 443)"
+
+ # A socket lingering in TIME_WAIT holds the port in its *local* address but
+ # is not a listener, so only the connection state can tell them apart.
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 127.0.0.1.8080 127.0.0.1.51000 TIME_WAIT
+tcp4 0 0 *.22 *.* LISTEN'
+ expect "BSD TIME_WAIT on local 8080 is free" "free" "$(port_listen_state 8080)"
+
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp6 0 0 ::1.8080 *.* LISTEN'
+ expect "BSD IPv6 LISTEN is busy" "busy" "$(port_listen_state 8080)"
+
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)'
+ expect "BSD header only is unknown" "unknown" "$(port_listen_state 8080)"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "4. Unknown never blocks startup"
+(
+ uname() { echo "Linux"; }
+ command_available() { return 1; }
+
+ expect "no probe tool is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # check_port must warn and let the server perform the authoritative bind.
+ err=$( (check_port "http://127.0.0.1:8080") 2>&1 >/dev/null )
+ rc=$?
+ expect "unknown exits 0" "0" "$rc"
+ if [[ "$err" == *"could not determine"* ]]; then
+ pass "unknown warns on stderr"
+ else
+ fail "unknown warns on stderr" "stderr was: $err"
+ fi
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "5. Real listener on an ephemeral port"
+if command -v python3 >/dev/null 2>&1; then
+ PORT_FILE=$(mktemp)
+ # Cover the temp file from the moment it exists, then widen the trap to the
+ # child as soon as there is a pid; registering only after the fork leaves a
+ # window where an interrupt orphans the listener for its full 30s sleep.
+ trap 'rm -f "$PORT_FILE" "$RESULTS"' EXIT
+ python3 -c '
+import socket, sys, time
+s = socket.socket()
+s.bind(("127.0.0.1", 0))
+s.listen(1)
+print(s.getsockname()[1])
+sys.stdout.flush()
+time.sleep(30)
+' > "$PORT_FILE" &
+ PY_PID=$!
+ trap 'kill "$PY_PID" 2>/dev/null; rm -f "$PORT_FILE" "$RESULTS"' EXIT
+
+ BOUND=""
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
+ BOUND=$(head -1 "$PORT_FILE" 2>/dev/null)
+ [[ -n "$BOUND" ]] && break
+ # Whole seconds only: fractional sleep is not POSIX, and this suite runs
+ # with `set -u` but no `-e`, so a busybox sleep would fail silently and
+ # spin all ten iterations instantly.
+ sleep 1
+ done
+
+ if [[ -z "$BOUND" ]] || ! kill -0 "$PY_PID" 2>/dev/null; then
+ fail "listener bound an ephemeral port" "child did not report a port"
+ else
+ pass "listener bound an ephemeral port ($BOUND)"
+ expect "bound port is busy" "busy" "$(port_listen_state "$BOUND")"
+ (check_port "http://127.0.0.1:$BOUND" >/dev/null 2>&1)
+ expect "check_port exits 1 on the bound port" "1" "$?"
+
+ # A port that was bound and released must not read as busy.
+ FREE=$(python3 -c 'import socket
+s = socket.socket()
+s.bind(("127.0.0.1", 0))
+p = s.getsockname()[1]
+s.close()
+print(p)')
+ expect "released port is not busy" "0" "$([[ "$(port_listen_state "$FREE")" == "busy" ]] && echo 1 || echo 0)"
+ fi
+
+ kill "$PY_PID" 2>/dev/null
+ wait "$PY_PID" 2>/dev/null
+ rm -f "$PORT_FILE"
+ # Restore the script-level handler rather than clearing it, so the tally
+ # file stays covered for the remaining sections.
+ trap 'rm -f "$RESULTS"' EXIT
+else
+ echo " SKIP real listener test: python3 not available"
+fi
+
+# --------------------------------------------------------------------------
+echo ""
+echo "6. download() rename failure is reported"
+(
+ WORK=$(mktemp -d)
+ trap 'rm -rf "$WORK"' EXIT
+
+ command_available() { [[ "$1" == "curl" ]]; }
+ curl() {
+ # Write to the -o destination so a temp file exists to rename.
+ local out=""
+ while [[ $# -gt 0 ]]; do
+ [[ "$1" == "-o" ]] && { out="$2"; shift; }
+ shift
+ done
+ echo "payload" > "$out"
+ return 0
+ }
+ # Simulate a rename that fails (read-only target, cross-device, ...).
+ mv() { return 1; }
+
+ if download "$WORK" "https://example.com/pkg.tar.gz"; then
+ fail "download reports rename failure" "download returned 0 after mv failed"
+ else
+ pass "download reports rename failure"
+ fi
+
+ if [[ -e "$WORK/pkg.tar.gz" ]]; then
+ fail "failed rename leaves no destination" "$WORK/pkg.tar.gz exists"
+ else
+ pass "failed rename leaves no destination"
+ fi
+
+ leftover=$(find "$WORK" -name '.pkg.tar.gz.*' 2>/dev/null | wc -l | tr -d ' ')
+ expect "failed rename cleans its temp file" "0" "$leftover"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "7. Startup probe is bounded"
+(
+ WORK=$(mktemp -d)
+ cd "$WORK" || exit 1
+ trap 'cd /; rm -rf "$WORK"' EXIT
+
+ ARGS_FILE="$WORK/curl-args"
+ SLEEP_FILE="$WORK/sleep-args"
+ : > "$SLEEP_FILE"
+ curl() { echo "$*" >> "$ARGS_FILE"; echo "000"; return 28; }
+ # Record what the retry pause asks for, but still take it, so the
+ # end-to-end duration below stays a real measurement.
+ sleep() { echo "$1" >> "$SLEEP_FILE"; command sleep "$1"; }
+ process_status() { return 0; }
+ ps() { return 0; }
+
+ TIMEOUT_S=1
+ START_S=$(date '+%s')
+ wait_for_startup "$$" "test-server" "http://127.0.0.1:1" "$TIMEOUT_S" >/dev/null 2>&1
Review Comment:
Fixed in `ee8f5559`. The test now captures `wait_for_startup()` status and requires exit 1, then parses every recorded curl call and requires both `--connect-timeout` and `--max-time` to be numeric, positive, and no greater than the one-second remaining deadline. The focused suite is 62/62 on macOS Bash 3.2. Mutation proof: hard-coding `--max-time 5` now fails the timeout-value assertion (61/62), and returning success after timeout now fails the status assertion (61/62); both mutations were green before this change. The 38-module Java 11 compile, repository-wide EditorConfig check, changed-shell syntax, workflow parse, and diff check also pass.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5083059763
### Status since imbajin’s last review
Addressing the blocking items from the later review rounds (including heads `9fdc941d` / `1f3f01e5` / `9b60fbb4`). Current tip: **`986c95f1`**.
**Port check correctness**
- Fixed: listener matching is endpoint-based (not bare port-only); hostname → numeric resolution before `ss`/`netstat` compare
- Fixed: IPv6 canonicalization via `normalize_addr()` (compressed vs expanded, brackets, zone scope, IPv4-mapped)
- Fixed: same-family wildcard conflicts only (IPv4 `0.0.0.0` / IPv6 `::` isolated)
- Fixed: tool failure fallthrough — nonzero `ss`/`netstat` does not count as “port free”; falls through to next probe
- Fixed: `/dev/tcp` bounded with `timeout` or `run_with_deadline()` (no open-ended hang)
- Fixed: `run_with_deadline` arg order `(cmd, deadline, args…)` — wrong order that printed `8080|2` is fixed
- Fixed: `/dev/tcp` host/port passed as `"$1"`/`"$2"` (no shell reparse of config text)
**URL / authority parsing**
- Fixed: authority cut at first `/`, `?`, or `#` (query/fragment no longer poisons port)
- Fixed: bracket IPv6 forms (`[::1]:8080` and scheme-less variants)
- Fixed: whitespace stripping on URL/host; octal-safe port via `$((10#port))`
**download() / PD–Store**
- Fixed: atomic download (temp + `mv` on success, `rm` on failure) — no partial-file poison
- Fixed: `curl -fL`, correct `-o` before `--`; wget progress as Bash 3.2-safe array
- Fixed: dead `check_port` removed from PD/Store; `command_available` inversion fixed
**CI / tests / cleanup**
- Fixed: `test-check-port.sh` — 40 mock-driven tests (ss / netstat / `/dev/tcp` / IPv6 / download / no-timeout watchdog)
- Fixed: no-timeout watchdog exercised; `local` outside function removed
- Fixed: EXIT trap registered early so Python child / temp file cleanup runs on `exit 1` path
- Fixed: PD/Store/Server start tests — `fuser` preflight on Linux, OS-aware cleanup, `STOP_SCRIPT` before kill
- Fixed: accidental revert of #3100 count-optm fix — branch now includes master (merge with #3102)
**Also**
- `process_num` / `process_id` no longer use truncated exit codes for PIDs/counts
- Darwin `free_memory` empty-value guards
- Server `read_property` / `ensure_package_exist` polish aligned with PD/Store
Local: `bash -n` clean; `test-check-port.sh` → **40 passed, 0 failed**.
Happy to take another look when you have time — thanks for the thorough reviews.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3666488631
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -185,16 +366,31 @@ function wait_for_startup() {
return 1
fi
- status=$(curl -I -sS -k -w "%{http_code}" -o /dev/null "$server_url" 2> "$error_file_name")
- if [[ $status -eq 200 || $status -eq 401 ]]; then
+ # Bound each probe by the time left in the overall deadline: without
+ # --max-time a single blackholed request blocks past ${timeout_s}s.
+ local remain_s=$((stop_s - now_s))
+ [ "$remain_s" -lt 1 ] && remain_s=1
Review Comment:
⚠️ The overall deadline can still be exceeded at its boundary. The inclusive loop permits another iteration when `now_s == stop_s`, then this line converts the expired `remain_s=0` into a fresh one-second curl budget. Two independent exact-head lanes reproduced two probes for `timeout_s=1`; when the deadline-edge probe consumed its advertised budget, elapsed time was about two seconds. Please refresh the clock before every curl and stop when no positive budget remains instead of clamping zero to one, then add a regression proving no probe begins at the deadline.
##########
.github/workflows/docker-build-ci.yml:
##########
@@ -47,6 +47,28 @@ jobs:
run: |
IMAGE_ID=$(docker build -q -f ${{ matrix.dockerfile }} .)
echo "Built: $IMAGE_ID"
+ echo "IMAGE_ID=$IMAGE_ID" >> "$GITHUB_ENV"
HC=$(docker inspect --format='{{json .Config.Healthcheck}}' "$IMAGE_ID")
echo "Healthcheck: $HC"
[[ "$HC" != "null" ]] || { echo "ERROR: HEALTHCHECK missing in ${{ matrix.dockerfile }}"; exit 1; }
+
+ # The startup preflight needs a socket-table tool, and the base image
+ # ships none of its own. Without one every start reports "unknown" and
+ # a duplicate start is no longer refused, so assert the image can
+ # actually answer. Only the server images run check_port.
+ # TODO(docker-ci): this pins the probe dependency, not the behaviour it
+ # protects. A full duplicate-start/stop check needs a booted server with
+ # a backend, which belongs with the e2e job rather than the image build.
+ - name: Port preflight can answer inside ${{ matrix.dockerfile }}
Review Comment:
⚠️ This image-level port-preflight check executes the changed `bin/util.sh`, but the workflow's PR filter still includes only Dockerfiles and `.dockerignore`. A later PR changing only the probed utility will skip the only check that proves the built image has a compatible socket-table tool. Please add `hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh` to `pull_request.paths`.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,395 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo "SKIP: util.sh not found at $UTIL_SH"
+ exit 0
Review Comment:
⚠️ Both Linux and macOS CI invoke this required contract test with an explicit production path, yet a missing or moved `util.sh` exits successfully without running any assertion. That can turn a broken test wiring change into a green check. Please fail when the explicitly selected utility is absent; reserve a skip result for a clearly optional invocation mode.
##########
hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh:
##########
@@ -286,26 +311,37 @@ download_and_verify() {
local url=$1
local filepath=$2
local expected_md5=$3
+ local actual_md5
- if [[ -f $filepath ]]; then
+ if [[ -f "$filepath" ]]; then
echo "File $filepath exists. Verifying MD5 checksum..."
- actual_md5=$(md5sum $filepath | awk '{ print $1 }')
- if [[ $actual_md5 != $expected_md5 ]]; then
+ actual_md5=$(md5sum -- "$filepath" | awk '{ print $1 }')
+ if [[ "$actual_md5" != "$expected_md5" ]]; then
echo "MD5 checksum verification failed for $filepath. Expected: $expected_md5, but got: $actual_md5"
echo "Deleting $filepath..."
- rm -f $filepath
+ rm -f -- "$filepath"
Review Comment:
⚠️ The checksum repair is still racy across concurrent starts. Two callers can both verify the same corrupt destination; one can download and atomically install a valid replacement at line 342, after which the other executes this stale removal and deletes the valid file. Please leave the destination in place while downloading and verifying a private temporary file, atomically replace it only after success, and use a per-destination lock if callers require stable success semantics; add a coordinated two-caller regression.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3663391671
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -185,8 +344,17 @@ function wait_for_startup() {
return 1
fi
- status=$(curl -I -sS -k -w "%{http_code}" -o /dev/null "$server_url" 2> "$error_file_name")
- if [[ $status -eq 200 || $status -eq 401 ]]; then
+ # Bound each probe by the time left in the overall deadline: without
+ # --max-time a single blackholed request blocks past ${timeout_s}s.
+ # TODO(wait_for_startup): overshoot is now bounded but not zero - the
+ # loop still sleeps 2s after a probe and only then re-reads the clock,
+ # so the total can exceed ${timeout_s}s by roughly one sleep interval.
+ local remain_s=$((stop_s - now_s))
+ [ "$remain_s" -lt 1 ] && remain_s=1
+ local connect_s=$((remain_s < 5 ? remain_s : 5))
+ status=$(curl -I -sS -k --connect-timeout "$connect_s" --max-time "$remain_s" \
Review Comment:
⚠️ Bounding each curl request does not make `wait_for_startup` honor its overall timeout: after an immediate failed probe the loop always sleeps two seconds before re-reading the clock. With `timeout_s=1`, an immediate curl failure still returns after about two seconds, and the new test checks only the curl flags rather than elapsed time. Please recompute the remaining deadline before sleeping, cap the sleep to that remainder, and assert the end-to-end duration.
##########
.github/workflows/server-ci.yml:
##########
@@ -70,17 +70,30 @@ jobs:
run: |
mvn clean compile -U -Dmaven.javadoc.skip=true -ntp
+ - name: Run check_port unit tests
+ if: ${{ env.BACKEND == 'rocksdb' }}
+ run: |
+ # Validates ss/netstat//dev/tcp replacement for lsof
Review Comment:
🧹 This comment still describes an `ss`/`netstat`/`/dev/tcp` fallback chain, but the exact-head implementation contains no `/dev/tcp` branch and returns `unknown` when neither socket-table tool is usable. Please update this and the matching comments below to describe the actual `ss`/`netstat` behavior.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,175 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
+ fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms textually; Java reads 08080 as decimal 8080.
+ # Arithmetic conversion must not happen before the value is bounded: Bash
+ # evaluates in 64-bit and wraps silently, so 18446744073709559616 would
+ # otherwise pass the range check as port 8000.
+ port="${port#"${port%%[!0]*}"}"
+ [[ -z "$port" ]] && return 1
+ (( ${#port} <= 5 )) || return 1
+ (( port >= 1 && port <= 65535 )) || return 1
+
+ echo "$port"
+}
+
+# Echo "busy", "free" or "unknown" for the given TCP port.
+#
+# Detection is deliberately port-only, matching the conservative behaviour of
+# the `lsof -i :PORT` call this replaces. Reproducing kernel socket semantics
+# in Bash - dual-stack IPV6_V6ONLY, wildcard versus specific binds, address
+# canonicalisation - produced more wrong answers than it prevented, so we only
+# ask "is anything already listening on this port?".
+#
+# Only LISTEN rows and only the local-address column are inspected, so an
+# unrelated outbound connection to the same port number is never mistaken for
+# a local listener. A tool that is missing, fails, or yields no recognisable
+# listener row reports "unknown" rather than "free".
+#
+# TODO(check_port): port-only matching ignores the listener's address, so a
+# listener bound to one local address (127.0.0.1:8080) reports the port busy
+# even when the server would bind a different one (192.168.1.5:8080). This is
+# deliberate - it is what `lsof -i :PORT` did, and it fails safe - but it can
+# refuse a bind that would have succeeded. If that is reported in practice,
+# revisit by comparing the local-address column instead of only its port.
+#
+# TODO(check_port): a host with genuinely zero LISTEN sockets is indistinguish-
+# able from a restricted or unparseable table, so both report "unknown" and
+# warn on every start. Distinguishing them needs a positive signal that the
+# table was readable (e.g. an exit status ss/netstat do not currently give).
+function port_listen_state() {
+ local port="$1"
+ local out
+ local os
+ os=$(uname)
+
+ # $4 is the local address for both `ss -ltn` and BSD `netstat -an`.
+ # Splitting on the last separator keeps IPv6 hextets (for example
+ # [2001:db8::80]:443) from being misread as the port.
+ local parser='
+ NF >= 4 && (!want_listen || $NF == "LISTEN") {
+ addr = $4
+ cut = 0
+ for (k = length(addr); k > 0; k--) {
+ if (substr(addr, k, 1) == sep) { cut = k; break }
+ }
+ if (cut == 0) next
+ rows++
+ if (substr(addr, cut + 1) == port) { found = 1; exit }
+ }
+ END {
+ if (found) print "busy"
+ else if (rows > 0) print "free"
+ else print "unknown"
+ }'
+
+ if [[ "$os" == "Darwin" || "$os" == *BSD* ]]; then
+ if command_available "netstat" && out=$(netstat -an -p tcp 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep="." -v want_listen=1 "$parser"
+ return 0
+ fi
+ else
+ # `ss -H -ltn` already restricts output to listening sockets.
+ if command_available "ss" && out=$(ss -H -ltn 2>/dev/null) && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=0 "$parser"
+ return 0
Review Comment:
⚠️ A successful but unparseable `ss` response returns `unknown` here immediately, so a working `netstat` fallback is never consulted. For example, with `ss` emitting a non-empty diagnostic banner and `netstat` reporting `0.0.0.0:8080 LISTEN`, `port_listen_state 8080` still returns `unknown` and lets startup reach the later bind failure. Please capture the parser result and return only for `busy` or `free`; continue to `netstat` on `unknown`, with a regression covering this fallback.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,175 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
+ fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms textually; Java reads 08080 as decimal 8080.
+ # Arithmetic conversion must not happen before the value is bounded: Bash
+ # evaluates in 64-bit and wraps silently, so 18446744073709559616 would
+ # otherwise pass the range check as port 8000.
+ port="${port#"${port%%[!0]*}"}"
+ [[ -z "$port" ]] && return 1
+ (( ${#port} <= 5 )) || return 1
+ (( port >= 1 && port <= 65535 )) || return 1
+
+ echo "$port"
+}
+
+# Echo "busy", "free" or "unknown" for the given TCP port.
+#
+# Detection is deliberately port-only, matching the conservative behaviour of
+# the `lsof -i :PORT` call this replaces. Reproducing kernel socket semantics
+# in Bash - dual-stack IPV6_V6ONLY, wildcard versus specific binds, address
+# canonicalisation - produced more wrong answers than it prevented, so we only
+# ask "is anything already listening on this port?".
+#
+# Only LISTEN rows and only the local-address column are inspected, so an
+# unrelated outbound connection to the same port number is never mistaken for
+# a local listener. A tool that is missing, fails, or yields no recognisable
+# listener row reports "unknown" rather than "free".
+#
+# TODO(check_port): port-only matching ignores the listener's address, so a
+# listener bound to one local address (127.0.0.1:8080) reports the port busy
+# even when the server would bind a different one (192.168.1.5:8080). This is
+# deliberate - it is what `lsof -i :PORT` did, and it fails safe - but it can
+# refuse a bind that would have succeeded. If that is reported in practice,
+# revisit by comparing the local-address column instead of only its port.
+#
+# TODO(check_port): a host with genuinely zero LISTEN sockets is indistinguish-
+# able from a restricted or unparseable table, so both report "unknown" and
+# warn on every start. Distinguishing them needs a positive signal that the
+# table was readable (e.g. an exit status ss/netstat do not currently give).
+function port_listen_state() {
+ local port="$1"
+ local out
+ local os
+ os=$(uname)
+
+ # $4 is the local address for both `ss -ltn` and BSD `netstat -an`.
+ # Splitting on the last separator keeps IPv6 hextets (for example
+ # [2001:db8::80]:443) from being misread as the port.
+ local parser='
+ NF >= 4 && (!want_listen || $NF == "LISTEN") {
+ addr = $4
+ cut = 0
+ for (k = length(addr); k > 0; k--) {
+ if (substr(addr, k, 1) == sep) { cut = k; break }
+ }
+ if (cut == 0) next
+ rows++
+ if (substr(addr, cut + 1) == port) { found = 1; exit }
+ }
+ END {
+ if (found) print "busy"
+ else if (rows > 0) print "free"
+ else print "unknown"
+ }'
+
+ if [[ "$os" == "Darwin" || "$os" == *BSD* ]]; then
+ if command_available "netstat" && out=$(netstat -an -p tcp 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep="." -v want_listen=1 "$parser"
+ return 0
+ fi
+ else
+ # `ss -H -ltn` already restricts output to listening sockets.
+ if command_available "ss" && out=$(ss -H -ltn 2>/dev/null) && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=0 "$parser"
+ return 0
+ fi
+ if command_available "netstat" && out=$(netstat -ltn 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=1 "$parser"
+ return 0
+ fi
fi
+
+ # TODO(check_port): with neither ss nor netstat present (some minimal
Review Comment:
⚠️ This `unknown` path is now the normal path in the official server images: both `hugegraph-server/Dockerfile` variants install `lsof`, but neither installs `ss` (`iproute2`) nor `netstat` (`net-tools`). The image therefore loses the occupied-port preflight even though it still ships the old probe dependency; a duplicate start can overwrite `bin/pid` before the new JVM fails to bind, leaving the original process unmanaged by the stop script. Please retain an `lsof` fallback or update the image dependency to a supported socket-table tool, and add an image-level duplicate-start/stop test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5102461486
**Self-review on `d4dc7d2b`** — things I found reading my own diff, none of them raised in review:
- PD/Store `process_num` / `process_id` still carried a changed contract while the server copy was already reverted. All three match master now — item 12 claimed this and it was only two-thirds true.
- The PD and Store images installed `lsof` purely for the `check_port` this PR deletes. Removed; they run no preflight, so unlike the server images nothing replaces it.
- Test suite: the tally file was cleaned only on the normal exit path — a SIGTERM mid-run leaked one temp file on the previous head, none now. And `sleep 0.5` → `sleep 1`, since fractional sleep is not POSIX and the suite runs `set -u` without `-e`.
- The image assertion tested "not `unknown`", which an empty result also satisfies; it now asserts `free` or `busy`.
**53 passed, 0 failed** on macOS `bash` 3.2 and Linux `bash` 5.2 against a real `ss`. The five implementation mutations each still fail it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3664127740
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,175 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
+ fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms textually; Java reads 08080 as decimal 8080.
+ # Arithmetic conversion must not happen before the value is bounded: Bash
+ # evaluates in 64-bit and wraps silently, so 18446744073709559616 would
+ # otherwise pass the range check as port 8000.
+ port="${port#"${port%%[!0]*}"}"
+ [[ -z "$port" ]] && return 1
+ (( ${#port} <= 5 )) || return 1
+ (( port >= 1 && port <= 65535 )) || return 1
+
+ echo "$port"
+}
+
+# Echo "busy", "free" or "unknown" for the given TCP port.
+#
+# Detection is deliberately port-only, matching the conservative behaviour of
+# the `lsof -i :PORT` call this replaces. Reproducing kernel socket semantics
+# in Bash - dual-stack IPV6_V6ONLY, wildcard versus specific binds, address
+# canonicalisation - produced more wrong answers than it prevented, so we only
+# ask "is anything already listening on this port?".
+#
+# Only LISTEN rows and only the local-address column are inspected, so an
+# unrelated outbound connection to the same port number is never mistaken for
+# a local listener. A tool that is missing, fails, or yields no recognisable
+# listener row reports "unknown" rather than "free".
+#
+# TODO(check_port): port-only matching ignores the listener's address, so a
+# listener bound to one local address (127.0.0.1:8080) reports the port busy
+# even when the server would bind a different one (192.168.1.5:8080). This is
+# deliberate - it is what `lsof -i :PORT` did, and it fails safe - but it can
+# refuse a bind that would have succeeded. If that is reported in practice,
+# revisit by comparing the local-address column instead of only its port.
+#
+# TODO(check_port): a host with genuinely zero LISTEN sockets is indistinguish-
+# able from a restricted or unparseable table, so both report "unknown" and
+# warn on every start. Distinguishing them needs a positive signal that the
+# table was readable (e.g. an exit status ss/netstat do not currently give).
+function port_listen_state() {
+ local port="$1"
+ local out
+ local os
+ os=$(uname)
+
+ # $4 is the local address for both `ss -ltn` and BSD `netstat -an`.
+ # Splitting on the last separator keeps IPv6 hextets (for example
+ # [2001:db8::80]:443) from being misread as the port.
+ local parser='
+ NF >= 4 && (!want_listen || $NF == "LISTEN") {
+ addr = $4
+ cut = 0
+ for (k = length(addr); k > 0; k--) {
+ if (substr(addr, k, 1) == sep) { cut = k; break }
+ }
+ if (cut == 0) next
+ rows++
+ if (substr(addr, cut + 1) == port) { found = 1; exit }
+ }
+ END {
+ if (found) print "busy"
+ else if (rows > 0) print "free"
+ else print "unknown"
+ }'
+
+ if [[ "$os" == "Darwin" || "$os" == *BSD* ]]; then
+ if command_available "netstat" && out=$(netstat -an -p tcp 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep="." -v want_listen=1 "$parser"
+ return 0
+ fi
+ else
+ # `ss -H -ltn` already restricts output to listening sockets.
+ if command_available "ss" && out=$(ss -H -ltn 2>/dev/null) && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=0 "$parser"
+ return 0
Review Comment:
Correct — the branch returned unconditionally, so a `ss` run that produced unusable output ended the search with a working `netstat` sitting right behind it. Fixed in `d93b6f9d`: the parser result is captured and only an actual answer returns.
```bash
if command_available "ss" && out=$(ss -H -ltn 2>/dev/null); then
if [[ -z "$out" ]]; then
echo "free"
return 0
fi
state=$(echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=0 "$parser")
case "$state" in
busy|free) echo "$state"; return 0 ;;
esac
fi
# netstat is tried next, same shape
```
`case busy|free` rather than `!= unknown` so an awk that dies and prints nothing also falls through instead of echoing an empty state.
One thing came out of your Docker comment that had to be fixed here too, or the image fix would only have been half of one. `ss -H -ltn` on a host with no listeners exits 0 and prints nothing, and a fresh container is exactly that. Treating empty as failure meant even an image with `iproute2` would warn on every clean start. `-H` suppresses the header, so there is no header to lose: a zero exit with no output is a positive "no TCP listeners", not an unreadable table. That is now the one case where empty is an answer, and it is the only reason `port_listen_state` returns `free` instead of `unknown` in the new image-build assertion.
Both netstat branches still print headers the parser drops, so an empty result there stays `unknown`. That is narrowed in the `TODO(check_port)` above the function rather than claimed as solved.
Regressions added (section 2 of the suite):
```
PASS ss empty output is free
PASS ss unparseable output is unknown
PASS unparseable ss falls back to netstat
PASS netstat fallback can also report free
PASS failed ss falls back to netstat
```
Restoring the early `return 0` fails exactly the two fallback cases; restoring `unknown`-on-empty fails exactly one.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3649547931
##########
hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeCountStrategy.java:
##########
@@ -277,28 +272,10 @@ private boolean doStrategy(final Step step) {
return false;
}
- final P<?> predicate = ((IsStep<?>) step.getNextStep()).getPredicate();
- if (this.hasNestedConnectivePredicate(predicate)) {
- return false;
- }
-
final Step parent = step.getTraversal().getParent().asStep();
Review Comment:
‼️ This PR's sole commit is based directly on `e960cc5` (`fix(server): skip unsafe count optm for nested predicates (#3100)`), but it removes that commit's entire 23-line `ConnectiveP` safety guard and simultaneously deletes all seven associated `CountStrategyCoreTest` regressions. Merging this shell-focused change would therefore reopen the wrong-result cases fixed by #3100 while hiding them from CI. Please remove both Java-file diffs from this PR and retain the complete #3100 implementation and tests.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,199 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Extract host
+ if [[ "$url" =~ \[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+ # Strip any leading/trailing whitespace
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ # Resolve hostname → numeric IPs so ss/netstat (which use -n) can match them.
+ # A "hostname" is anything that is not blank, a wildcard, or already numeric.
+ # If resolution fails, resolved_addrs stays empty and we fall back to /dev/tcp probe.
+ local resolved_addrs=""
+ local is_hostname=0
+ if [[ -n "$host" && "$host" != "0.0.0.0" && "$host" != "::" && "$host" != "*" ]] \
+ && ! [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
+ && ! [[ "$host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ is_hostname=1
+ if command_available "getent"; then
+ resolved_addrs=$(getent hosts "$host" 2>/dev/null | awk '{print $1}')
Review Comment:
⚠️ The new hostname-resolution phase runs synchronously without any deadline, before either bounded `/dev/tcp` branch. A slow or stuck NSS/DNS/LDAP lookup in `getent hosts` (and likewise `dscacheutil`) can therefore still hang startup despite the later 1-2 second probe watchdog. Please apply a hard deadline to resolution as well, fall through safely on timeout, and cover a blocking resolver in the shell tests.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,199 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
Review Comment:
⚠️ This extracts the port from the last colon in the entire URL rather than from its authority. `ServerOptionsTest.testUrlNormalizationPreservesPathCase` explicitly preserves URL paths, so `http://127.0.0.1:8080/path:9090` is checked as port 9090 and can miss an occupied 8080; a valid URL without an explicit port is skipped entirely instead of checking its HTTP/HTTPS default. Please parse the normalized URI authority, handle the scheme's default port explicitly, and add regressions for a colon in the path and for an omitted port.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,682 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# test-check-port.sh — Unit tests for check_port() in util.sh
+#
+# Strategy: each test runs check_port in a subshell that overrides
+# command_available() to control which probe branch is taken, and
+# overrides the tool functions (ss, netstat, timeout) to control
+# what they return — no real network connections needed.
+#
+# check_port calls `exit 1` when the port is in use, so the subshell
+# exits 1; it returns normally (exit 0) when the port is free.
+#
+# Usage: ./test-check-port.sh [path-to-hugegraph-static-dir]
+# path-to-hugegraph-static-dir: directory containing bin/util.sh
+# Defaults to current directory.
+# In CI: $TRAVIS_DIR/test-check-port.sh hugegraph-server/hugegraph-dist/src/assembly/static
+
+set -uo pipefail
+
+STATIC_DIR="${1:-$(pwd)}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+REPO_ROOT="$(cd "$(dirname "$0")/../../../../.." && pwd)"
+PD_UTIL_SH="$REPO_ROOT/hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh"
+STORE_UTIL_SH="$REPO_ROOT/hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh"
+
+PASS=0
+FAIL=0
+ERRORS=()
+
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+pass() { echo -e "${GREEN} PASS${NC} $1"; PASS=$((PASS + 1)); }
+fail() { echo -e "${RED} FAIL${NC} $1"; ERRORS+=("$1"); FAIL=$((FAIL + 1)); }
+section() { echo ""; echo "── $1 ──"; }
+
+echo ""
+echo "check_port() unit test suite"
+echo "util.sh: $UTIL_SH"
+echo ""
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo -e "${RED}ERROR:${NC} $UTIL_SH not found."
+ echo " Pass the HugeGraph static assembly dir as \$1"
+ exit 1
+fi
+
+# ── ss branch ─────────────────────────────────────────────────────────────────
+
+section "ss branch — IPv4"
+
+(
+ # shellcheck source=/dev/null
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: IPv4 port occupied → exit 1" \
+ || fail "ss: IPv4 port occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:9090 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: IPv4 port free → exit 0" \
+ || fail "ss: IPv4 port free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL with scheme (http://[::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: http://[::1]:8080 occupied → exit 1" \
+ || fail "ss: http://[::1]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: http://[::1]:8080 free → exit 0" \
+ || fail "ss: http://[::1]:8080 free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL without scheme ([::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::1]:8080 (no scheme) occupied → exit 1" \
+ || fail "ss: [::1]:8080 (no scheme) occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::1]:8080 (no scheme) free → exit 0" \
+ || fail "ss: [::1]:8080 (no scheme) free → expected exit 0, got 1"
+
+section "ss branch — wildcard 0.0.0.0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://0.0.0.0:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: 0.0.0.0:8080 occupied → exit 1" \
+ || fail "ss: 0.0.0.0:8080 occupied → expected exit 1, got 0"
+
+section "ss branch — wildcard ::"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::]:8080 occupied → exit 1" \
+ || fail "ss: [::]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::]:8080 free → exit 0" \
+ || fail "ss: [::]:8080 free → expected exit 0, got 1"
+
+# ── netstat branch ────────────────────────────────────────────────────────────
+
+section "netstat branch — Linux format (-ltn), occupied"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -ltn: port 8080 occupied → exit 1" \
+ || fail "netstat -ltn: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — Linux format (-ltn), free"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat -ltn: port 8080 free → exit 0" \
+ || fail "netstat -ltn: port 8080 free → expected exit 0, got 1"
+
+section "netstat branch — BSD/macOS fallback (-an), occupied"
+
+# Simulate netstat that produces no output for -ltn (Linux flag unsupported)
+# but outputs BSD-format lines for -an
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() {
+ if [[ "$1" == "-ltn" ]]; then
+ return 1 # flag not supported on BSD
+ fi
+ echo "tcp4 0 0 *.8080 *.* LISTEN"
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -an BSD: port 8080 occupied → exit 1" \
+ || fail "netstat -an BSD: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — IP octet false-positive guard"
+
+# Port 80 check; netstat output contains 192.168.80.1:443
+# The .80 in the IP address must NOT match port 80
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 192.168.80.1:443 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:80"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat: IP octet .80 does not false-positive for port 80 → exit 0" \
+ || fail "netstat: IP octet .80 false-positived for port 80 → expected exit 0, got 1"
+
+section "ss branch — host dot-escaping guard"
+
+# Host 127.0.0.1 must be matched literally: a listener whose address merely
+# matches the pattern with '.' as a regex wildcard (127a0b0c1) must NOT count
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 127a0b0c1:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: unescaped-dot lookalike 127a0b0c1 does not false-positive → exit 0" \
+ || fail "ss: unescaped-dot lookalike 127a0b0c1 false-positived → expected exit 0, got 1"
+
+# ── /dev/tcp fallback branch ──────────────────────────────────────────────────
+
+section "/dev/tcp fallback — timeout available, port occupied"
+
+# timeout exits 0 → connection succeeded → port in use
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ # Assert correct invocation: timeout 1 bash -c SCRIPT _ HOST PORT
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 0
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "/dev/tcp+timeout: connection succeeded (exit 0) → port occupied → exit 1" \
+ || fail "/dev/tcp+timeout: connection succeeded → expected exit 1, got 0"
+
+section "/dev/tcp fallback — timeout available, port free"
+
+# timeout exits 1 → connection refused → port free
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 1
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "/dev/tcp+timeout: connection refused (exit 1) → port free → exit 0" \
+ || fail "/dev/tcp+timeout: connection refused → expected exit 0, got 1"
+
+section "/dev/tcp fallback — real loopback (ephemeral port)"
+
+# Start Python server on ephemeral port 0, capture actual port from child stdout
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ # Mock timeout: on hosts without timeout (macOS), run the probe directly.
+ # The probe args are: timeout 1 bash -c SCRIPT _ HOST PORT
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*" >&2; return 2; }
+ # Run the probe with a 2-second hard deadline via background + watchdog
+ bash -c "$4" "$5" "$6" "$7" 2>/dev/null &
+ local probe_pid=$!
+ (sleep 2; kill -9 "$probe_pid" 2>/dev/null) &
+ local watchdog_pid=$!
+ wait "$probe_pid" 2>/dev/null
+ local rc=$?
+ kill -9 "$watchdog_pid" 2>/dev/null
+ wait "$watchdog_pid" 2>/dev/null
+ return $rc
+ }
+ # Use a temp file to capture the bound port from child
+ port_file=$(mktemp)
+ trap "rm -f $port_file" EXIT
+
+ # Start Python server that prints the bound port to stdout
+ python3 -c "
+import socket
+s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+s.bind(('127.0.0.1', 0))
+s.listen(1) # actually listen so /dev/tcp can connect
+port = s.getsockname()[1]
+print(port, flush=True)
+import time
+time.sleep(30) # keep server alive
+" > "$port_file" 2>/dev/null &
+ PY_PID=$!
+ # Poll for port file up to ~4s (Python cold-start can exceed 0.5s on busy CI)
+ bound_port=""
+ for _ in $(seq 1 40); do
+ bound_port=$(head -1 "$port_file" 2>/dev/null)
+ [[ -n "$bound_port" ]] && break
+ kill -0 $PY_PID 2>/dev/null || break
+ sleep 0.1
+ done
+ if [[ -z "$bound_port" || ! "$bound_port" =~ ^[0-9]+$ ]]; then
+ echo "SKIP: failed to get bound port"
+ kill -9 $PY_PID 2>/dev/null || true
+ exit 77
+ fi
+ # Verify child is alive
+ if ! kill -0 $PY_PID 2>/dev/null; then
+ echo "SKIP: Python child died"
+ exit 77
+ fi
+ check_port "http://127.0.0.1:$bound_port"
Review Comment:
⚠️ On the expected occupied-port path, `check_port` executes `exit 1`, so the following `rc`, `kill`, and `wait` cleanup is unreachable. The EXIT trap only removes the temporary file, leaving the Python listener alive for up to 30 seconds after every successful real-probe test. Please register cleanup of `PY_PID` in the EXIT trap (including `wait`), or invoke `check_port` in a nested subshell so the parent can always reap the child.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3649890156
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,229 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme (http://, https://, or none) and path.
+ # This ensures port is extracted from host:port, not from a colon in the path.
+ local authority
+ if [[ "$url" =~ ^[a-zA-Z][a-zA-Z0-9+.-]*:// ]]; then
+ authority=$(echo "$url" | sed 's|^[^/]*://||; s|/.*||')
+ else
+ authority=$(echo "$url" | sed 's|/.*||')
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host and port from authority.
+ # Assumes IPv6 is bracketed (e.g. [::1]:8080). Unbracketed IPv6 like
+ # ::1:8080 would misparse as host=::, port=1. ServerOptions does not
+ # enforce bracketing at the config layer; if this ever fires on bad input
+ # the downstream bind would fail with a clearer error than the preflight.
+ if [[ "$authority" =~ ^\[([^\]]*)\]:([0-9]+)$ ]]; then
+ # IPv6 with port: [::1]:8080
+ host="${BASH_REMATCH[1]}"
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" =~ :([0-9]+)$ ]]; then
+ # IPv4 or hostname with port: 127.0.0.1:8080
+ port="${BASH_REMATCH[1]}"
+ host="${authority%:*}"
+ else
+ # No explicit port in authority
+ host="$authority"
+ port=""
+ fi
+
+ # Handle default ports from scheme when no explicit port given
+ if [[ -z "$port" ]]; then
+ if [[ "$url" == https://* ]]; then
+ port="443"
+ elif [[ "$url" == http://* ]]; then
+ port="80"
+ fi
+ fi
+
+ if [[ -z "$port" ]]; then
+ return 0
+ fi
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Strip any leading/trailing whitespace from host
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ # Resolve hostname → numeric IPs so ss/netstat (which use -n) can match them.
+ # A "hostname" is anything that is not blank, a wildcard, or already numeric.
+ # Resolution runs with a deadline to prevent hangs from slow/stuck DNS/LDAP.
+ # If timeout is unavailable, skip resolution and fall through to bounded /dev/tcp.
+ local resolved_addrs=""
+ local is_hostname=0
+ if [[ -n "$host" && "$host" != "0.0.0.0" && "$host" != "::" && "$host" != "*" ]] \
+ && ! [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
+ && ! [[ "$host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ is_hostname=1
+ if command_available "getent" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 getent hosts "$host" 2>/dev/null | awk '{print $1}')
+ elif command_available "dscacheutil" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 dscacheutil -q host -a name "$host" 2>/dev/null \
+ | awk '/ip_address:/{print $2}')
+ fi
+ # If timeout unavailable or resolution times out, resolved_addrs stays empty
+ # and we fall through to the bounded /dev/tcp probe (2s watchdog) instead.
+ fi
+
+ local linux_pattern
+ local bsd_pattern
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ # Wildcard patterns match any address family (IPv4 or IPv6) on the port
+ # Note: This treats IPv4 and IPv6 wildcard listeners as conflicts, which is conservative
+ # but may be overly strict for dual-stack systems where they can coexist
+ linux_pattern=":${port}([[:space:]]|$)"
+ bsd_pattern="(\.|:)${port}([[:space:]]|$)"
+ else
+ # For hostnames, only use resolved numeric addresses (ss/netstat report numeric).
+ # Keep wildcard matching family-aware to avoid cross-family false conflicts.
+ local addr_alts=""
+ local match_ipv4=0
+ local match_ipv6=0
+ if [[ $is_hostname -eq 1 ]]; then
+ # Hostname: use resolved addresses and infer address family set
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ local esc_addr="${addr//./\\.}"
+ if [[ "$addr" == *":"* ]]; then
+ esc_addr="${esc_addr//:/\\:}"
+ match_ipv6=1
+ else
+ match_ipv4=1
+ fi
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="${esc_addr}|\[${esc_addr}\]"
+ else
+ addr_alts="${addr_alts}|${esc_addr}|\[${esc_addr}\]"
+ fi
+ done <<< "$resolved_addrs"
+ else
+ # Numeric address: use it directly and infer address family
+ local esc_host="${host//./\\.}"
+ if [[ "$host" == *":"* ]]; then
+ esc_host="${esc_host//:/\\:}"
+ match_ipv6=1
+ else
+ match_ipv4=1
+ fi
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="${esc_host}|\[${esc_host}\]"
+ else
+ addr_alts="${addr_alts}|${esc_host}|\[${esc_host}\]"
+ fi
+ fi
+ if [[ $match_ipv4 -eq 1 ]]; then
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="0\.0\.0\.0|\*"
+ else
+ addr_alts="${addr_alts}|0\.0\.0\.0|\*"
+ fi
+ fi
+ if [[ $match_ipv6 -eq 1 ]]; then
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="\[::\]|::"
+ else
+ addr_alts="${addr_alts}|\[::\]|::"
+ fi
+ fi
+ # Pattern: addresses followed by colon and port, with whitespace/end anchor
+ # (avoids IPv6 hextet false positives without GNU-specific \b)
+ linux_pattern="(${addr_alts}):${port}([[:space:]]|$)"
+ bsd_pattern="(${addr_alts})(\\.|:)${port}([[:space:]]|$)"
+ fi
+
+ local in_use=0
+ local port_checked=0
+ local out=""
+
+ if command_available "ss"; then
+ if out=$(ss -ltn 2>/dev/null); then
+ # Only mark as checked if we can actually match the configured endpoint.
+ # For unresolved hostnames, fall through to the /dev/tcp probe instead.
+ if [[ $is_hostname -eq 0 || -n "$resolved_addrs" ]]; then
+ port_checked=1
+ if echo "$out" | grep -qE "$linux_pattern"; then
+ in_use=1
+ fi
+ fi
+ else
+ # ss command failed (tool present but exited non-zero), try next tool
+ port_checked=0
+ fi
+ fi
+
+ if [[ $port_checked -eq 0 ]] && command_available "netstat"; then
+ if out=$(netstat -ltn 2>/dev/null) && echo "$out" | grep -qi "listen"; then
+ if [[ $is_hostname -eq 0 || -n "$resolved_addrs" ]]; then
+ port_checked=1
+ if echo "$out" | grep -qE "$linux_pattern" || echo "$out" | grep -qE "$bsd_pattern"; then
+ in_use=1
+ fi
+ fi
+ elif out=$(netstat -an 2>/dev/null); then
Review Comment:
⚠️ A zero exit status does not prove that `netstat -an` produced a usable listener table. In restricted environments it can return success with empty or diagnostic-only output; this branch then skips `/dev/tcp` and may report an occupied endpoint as free. Please model this result as `unknown`: set `port_checked` only after recognizing valid listener rows, otherwise continue to the bounded fallback. Add regressions for exit 0 with empty and unparseable output.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,684 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# test-check-port.sh — Unit tests for check_port() in util.sh
+#
+# Strategy: each test runs check_port in a subshell that overrides
+# command_available() to control which probe branch is taken, and
+# overrides the tool functions (ss, netstat, timeout) to control
+# what they return — no real network connections needed.
+#
+# check_port calls `exit 1` when the port is in use, so the subshell
+# exits 1; it returns normally (exit 0) when the port is free.
+#
+# Usage: ./test-check-port.sh [path-to-hugegraph-static-dir]
+# path-to-hugegraph-static-dir: directory containing bin/util.sh
+# Defaults to current directory.
+# In CI: $TRAVIS_DIR/test-check-port.sh hugegraph-server/hugegraph-dist/src/assembly/static
+
+set -uo pipefail
+# -u: fail on undefined variables (catches typos in test assertions)
+# -o pipefail: pipeline exit status is the last non-zero component
+# shellcheck disable=SC1090,SC1091 # UTIL_SH / PD_UTIL_SH sourced dynamically at runtime
+
+STATIC_DIR="${1:-$(pwd)}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+REPO_ROOT="$(cd "$(dirname "$0")/../../../../.." && pwd)"
+PD_UTIL_SH="$REPO_ROOT/hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh"
+STORE_UTIL_SH="$REPO_ROOT/hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh"
+
+PASS=0
+FAIL=0
+ERRORS=()
+
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+pass() { echo -e "${GREEN} PASS${NC} $1"; PASS=$((PASS + 1)); }
+fail() { echo -e "${RED} FAIL${NC} $1"; ERRORS+=("$1"); FAIL=$((FAIL + 1)); }
+section() { echo ""; echo "── $1 ──"; }
+
+echo ""
+echo "check_port() unit test suite"
+echo "util.sh: $UTIL_SH"
+echo ""
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo -e "${RED}ERROR:${NC} $UTIL_SH not found."
+ echo " Pass the HugeGraph static assembly dir as \$1"
+ exit 1
+fi
+
+# ── ss branch ─────────────────────────────────────────────────────────────────
+
+section "ss branch — IPv4"
+
+(
+ # shellcheck source=/dev/null
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: IPv4 port occupied → exit 1" \
+ || fail "ss: IPv4 port occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:9090 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: IPv4 port free → exit 0" \
+ || fail "ss: IPv4 port free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL with scheme (http://[::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: http://[::1]:8080 occupied → exit 1" \
+ || fail "ss: http://[::1]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: http://[::1]:8080 free → exit 0" \
+ || fail "ss: http://[::1]:8080 free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL without scheme ([::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::1]:8080 (no scheme) occupied → exit 1" \
+ || fail "ss: [::1]:8080 (no scheme) occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::1]:8080 (no scheme) free → exit 0" \
+ || fail "ss: [::1]:8080 (no scheme) free → expected exit 0, got 1"
+
+section "ss branch — wildcard 0.0.0.0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://0.0.0.0:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: 0.0.0.0:8080 occupied → exit 1" \
+ || fail "ss: 0.0.0.0:8080 occupied → expected exit 1, got 0"
+
+section "ss branch — wildcard ::"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::]:8080 occupied → exit 1" \
+ || fail "ss: [::]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::]:8080 free → exit 0" \
+ || fail "ss: [::]:8080 free → expected exit 0, got 1"
+
+# ── netstat branch ────────────────────────────────────────────────────────────
+
+section "netstat branch — Linux format (-ltn), occupied"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -ltn: port 8080 occupied → exit 1" \
+ || fail "netstat -ltn: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — Linux format (-ltn), free"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat -ltn: port 8080 free → exit 0" \
+ || fail "netstat -ltn: port 8080 free → expected exit 0, got 1"
+
+section "netstat branch — BSD/macOS fallback (-an), occupied"
+
+# Simulate netstat that produces no output for -ltn (Linux flag unsupported)
+# but outputs BSD-format lines for -an
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() {
+ if [[ "$1" == "-ltn" ]]; then
+ return 1 # flag not supported on BSD
+ fi
+ echo "tcp4 0 0 *.8080 *.* LISTEN"
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -an BSD: port 8080 occupied → exit 1" \
+ || fail "netstat -an BSD: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — IP octet false-positive guard"
+
+# Port 80 check; netstat output contains 192.168.80.1:443
+# The .80 in the IP address must NOT match port 80
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 192.168.80.1:443 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:80"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat: IP octet .80 does not false-positive for port 80 → exit 0" \
+ || fail "netstat: IP octet .80 false-positived for port 80 → expected exit 0, got 1"
+
+section "ss branch — host dot-escaping guard"
+
+# Host 127.0.0.1 must be matched literally: a listener whose address merely
+# matches the pattern with '.' as a regex wildcard (127a0b0c1) must NOT count
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 127a0b0c1:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: unescaped-dot lookalike 127a0b0c1 does not false-positive → exit 0" \
+ || fail "ss: unescaped-dot lookalike 127a0b0c1 false-positived → expected exit 0, got 1"
+
+# ── /dev/tcp fallback branch ──────────────────────────────────────────────────
+
+section "/dev/tcp fallback — timeout available, port occupied"
+
+# timeout exits 0 → connection succeeded → port in use
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ # Assert correct invocation: timeout 1 bash -c SCRIPT _ HOST PORT
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 0
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "/dev/tcp+timeout: connection succeeded (exit 0) → port occupied → exit 1" \
+ || fail "/dev/tcp+timeout: connection succeeded → expected exit 1, got 0"
+
+section "/dev/tcp fallback — timeout available, port free"
+
+# timeout exits 1 → connection refused → port free
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 1
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "/dev/tcp+timeout: connection refused (exit 1) → port free → exit 0" \
+ || fail "/dev/tcp+timeout: connection refused → expected exit 0, got 1"
+
+section "/dev/tcp fallback — real loopback (ephemeral port)"
+
+# Start Python server on ephemeral port 0, capture actual port from child stdout
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
Review Comment:
⚠️ Every `/dev/tcp` test reports `timeout` as available or reimplements it with a mock, including this macOS-oriented case. The production no-`timeout` watchdog is never exercised, although stock macOS depends on its kill/wait/deadline behavior. Please test the actual branch with `command_available timeout` returning false for occupied, refused, and deadline cases, and assert that both child processes are reaped.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5120152909
@imbajin Ready for re-review at `18ab2f8b`.
The four findings from your latest review are addressed in `8b4e01ae`; each inline thread now has the specific fix and regression evidence. Current-head validation includes:
- focused contract suite: 60 passed, 0 failed on macOS Bash 3.2
- Linux and both macOS server checks, including the port suite: passed
- all four Docker image builds: passed
- Store foreground startup suite: passed
- all required checks, including CodeQL: passed
- implementer self-review plus a fresh independent read-only review: no actionable findings
Codecov is intentionally treated as non-blocking.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3662057853
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,170 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms; Java reads 08080 as decimal 8080.
+ port=$((10#$port))
Review Comment:
Confirmed and fixed in `a413325b`. Your repro is correct, and the case is a bit wider than the value you found.
`18446744073709551617` wraps to `1`, but the worse shape is a value that wraps into a plausible port:
```
before: parse_port_from_url "http://127.0.0.1:18446744073709559616" -> 8000
after : rc=1 (skipped)
```
That one mattered more than the wrap to `1`: the preflight would have aborted startup with "The port 8000 has already been used", naming a port the operator never configured, for what is really a malformed value.
The fix normalises the leading-zero form textually and bounds the digit count before any arithmetic:
```bash
port="${port#"${port%%[!0]*}"}"
[[ -z "$port" ]] && return 1
(( ${#port} <= 5 )) || return 1
(( port >= 1 && port <= 65535 )) || return 1
```
Leading zeroes are still accepted, since `new URI("http://127.0.0.1:0000000000000008080").getPort()` returns `8080` — I checked rather than assumed. `00000` returns `0` there and is skipped.
Four cases added to the URL-parsing table: both wrapping values, `00000`, and the long leading-zero form. The suite is **48 passed, 0 failed**, and restoring `port=$((10#$port))` fails exactly the two overflow cases, so they are not vacuous.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3664126053
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -118,18 +119,175 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
-function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+# Extract a validated TCP port from a configured server URL.
+# Echoes the port on success. Returns 1 when the value carries no usable port
+# or is ambiguous, in which case the caller skips the preflight.
+function parse_port_from_url() {
+ local url="$1"
+
+ # ServerOptions tolerates surrounding whitespace, so strip it first.
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+ [[ -z "$url" ]] && return 1
+
+ # The scheme is optional and case-insensitive.
+ local scheme="" rest="$url"
+ if [[ "$url" == *"://"* ]]; then
+ scheme=$(echo "${url%%://*}" | tr '[:upper:]' '[:lower:]')
+ rest="${url#*://}"
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
- echo "The port $port has already been used"
- exit 1
+
+ # The authority ends at the first '/', '?' or '#'.
+ local authority="${rest%%[/?#]*}"
+ [[ -z "$authority" ]] && return 1
+
+ # Drop any userinfo prefix; its colon would otherwise look like an
+ # unbracketed IPv6 separator.
+ authority="${authority##*@}"
+ [[ -z "$authority" ]] && return 1
+
+ local port=""
+ if [[ "$authority" =~ ^\[[^]]*\](:([0-9]+))?$ ]]; then
+ # Bracketed IPv6, with or without a port: [::1] or [::1]:8080
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" == *:*:* ]]; then
+ # Unbracketed IPv6 is ambiguous: in "::1:8080" the trailing group may
+ # be a port or another hextet. Refuse to guess.
+ # TODO(check_port): no preflight runs at all for this form. If
+ # ServerOptions ever guarantees a normalized bracketed value here, this
+ # branch can resolve the port instead of skipping the check.
+ echo "WARN: ambiguous IPv6 authority '$authority' in server URL;" \
+ "use bracket notation such as [::1]:8080." >&2
+ return 1
+ elif [[ "$authority" == *:* ]]; then
+ port="${authority##*:}"
+ fi
+
+ # Fall back to the scheme's default port.
+ # TODO(check_port): a scheme-less value with no explicit port (e.g. plain
+ # "127.0.0.1") has no derivable port, so it is skipped rather than guessed.
+ # Reading the configured default from ServerOptions would close this gap.
+ if [[ -z "$port" ]]; then
+ case "$scheme" in
+ http) port="80" ;;
+ https) port="443" ;;
+ *) return 1 ;;
+ esac
+ fi
+
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ # Normalise leading-zero forms textually; Java reads 08080 as decimal 8080.
+ # Arithmetic conversion must not happen before the value is bounded: Bash
+ # evaluates in 64-bit and wraps silently, so 18446744073709559616 would
+ # otherwise pass the range check as port 8000.
+ port="${port#"${port%%[!0]*}"}"
+ [[ -z "$port" ]] && return 1
+ (( ${#port} <= 5 )) || return 1
+ (( port >= 1 && port <= 65535 )) || return 1
+
+ echo "$port"
+}
+
+# Echo "busy", "free" or "unknown" for the given TCP port.
+#
+# Detection is deliberately port-only, matching the conservative behaviour of
+# the `lsof -i :PORT` call this replaces. Reproducing kernel socket semantics
+# in Bash - dual-stack IPV6_V6ONLY, wildcard versus specific binds, address
+# canonicalisation - produced more wrong answers than it prevented, so we only
+# ask "is anything already listening on this port?".
+#
+# Only LISTEN rows and only the local-address column are inspected, so an
+# unrelated outbound connection to the same port number is never mistaken for
+# a local listener. A tool that is missing, fails, or yields no recognisable
+# listener row reports "unknown" rather than "free".
+#
+# TODO(check_port): port-only matching ignores the listener's address, so a
+# listener bound to one local address (127.0.0.1:8080) reports the port busy
+# even when the server would bind a different one (192.168.1.5:8080). This is
+# deliberate - it is what `lsof -i :PORT` did, and it fails safe - but it can
+# refuse a bind that would have succeeded. If that is reported in practice,
+# revisit by comparing the local-address column instead of only its port.
+#
+# TODO(check_port): a host with genuinely zero LISTEN sockets is indistinguish-
+# able from a restricted or unparseable table, so both report "unknown" and
+# warn on every start. Distinguishing them needs a positive signal that the
+# table was readable (e.g. an exit status ss/netstat do not currently give).
+function port_listen_state() {
+ local port="$1"
+ local out
+ local os
+ os=$(uname)
+
+ # $4 is the local address for both `ss -ltn` and BSD `netstat -an`.
+ # Splitting on the last separator keeps IPv6 hextets (for example
+ # [2001:db8::80]:443) from being misread as the port.
+ local parser='
+ NF >= 4 && (!want_listen || $NF == "LISTEN") {
+ addr = $4
+ cut = 0
+ for (k = length(addr); k > 0; k--) {
+ if (substr(addr, k, 1) == sep) { cut = k; break }
+ }
+ if (cut == 0) next
+ rows++
+ if (substr(addr, cut + 1) == port) { found = 1; exit }
+ }
+ END {
+ if (found) print "busy"
+ else if (rows > 0) print "free"
+ else print "unknown"
+ }'
+
+ if [[ "$os" == "Darwin" || "$os" == *BSD* ]]; then
+ if command_available "netstat" && out=$(netstat -an -p tcp 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep="." -v want_listen=1 "$parser"
+ return 0
+ fi
+ else
+ # `ss -H -ltn` already restricts output to listening sockets.
+ if command_available "ss" && out=$(ss -H -ltn 2>/dev/null) && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=0 "$parser"
+ return 0
+ fi
+ if command_available "netstat" && out=$(netstat -ltn 2>/dev/null) \
+ && [[ -n "$out" ]]; then
+ echo "$out" | awk -v port="$port" -v sep=":" -v want_listen=1 "$parser"
+ return 0
+ fi
fi
+
+ # TODO(check_port): with neither ss nor netstat present (some minimal
Review Comment:
Confirmed, and it is worse than a lost warning. Checked the base image rather than reasoning about it:
```
$ docker run --rm eclipse-temurin:11-jre-jammy \
bash -c 'for t in ss netstat lsof ip; do printf "%-8s " $t; command -v $t || echo MISSING; done'
ss MISSING
netstat MISSING
lsof MISSING
ip MISSING
```
So the image installs `lsof` for a probe nothing calls any more, and ships nothing the new probe can use. Against a real listener, sourcing the exact-head `util.sh` inside that image:
```
as shipped (lsof): port 8080 -> unknown port 9999 -> unknown
with iproute2: port 8080 -> busy port 9999 -> free
```
Fixed in `d93b6f9d` by taking the second option you offered: `lsof` is replaced with `iproute2` in `hugegraph-server/Dockerfile` and `Dockerfile-hstore`. Retaining an `lsof` fallback would put back the call whose fd-table scan is the hang this PR exists to fix, and it would be reached exactly where it hurts — a container with a large `ulimit -n`.
Flagging one judgement call: I **removed** `lsof` rather than keeping it alongside `iproute2`. Nothing shipped calls it (`checksocket.sh` shells out to `CheckSocket`, `docker-entrypoint.sh` does not use it), so it was only a debugging convenience like `vim`. Say the word if you would rather keep both.
On the image-level test: the cheap half is in, the expensive half is not. `docker-build-ci.yml` already builds each Dockerfile on any PR touching `**/Dockerfile*`, so it now asserts the probe can answer inside the built image:
```yaml
STATE=$(docker run --rm "$IMAGE_ID" bash -c \
'source /hugegraph-server/bin/util.sh && port_listen_state 8080')
[[ "$STATE" != "unknown" ]] || { echo "ERROR: no usable socket-table tool"; exit 1; }
```
That pins the dependency, not the duplicate-start behaviour it protects. A real duplicate-start/stop check needs a booted server with a backend, which belongs with the e2e job rather than the image build — left as `TODO(docker-ci)` in the workflow rather than half-done here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3664130168
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -185,8 +344,17 @@ function wait_for_startup() {
return 1
fi
- status=$(curl -I -sS -k -w "%{http_code}" -o /dev/null "$server_url" 2> "$error_file_name")
- if [[ $status -eq 200 || $status -eq 401 ]]; then
+ # Bound each probe by the time left in the overall deadline: without
+ # --max-time a single blackholed request blocks past ${timeout_s}s.
+ # TODO(wait_for_startup): overshoot is now bounded but not zero - the
+ # loop still sleeps 2s after a probe and only then re-reads the clock,
+ # so the total can exceed ${timeout_s}s by roughly one sleep interval.
+ local remain_s=$((stop_s - now_s))
+ [ "$remain_s" -lt 1 ] && remain_s=1
+ local connect_s=$((remain_s < 5 ? remain_s : 5))
+ status=$(curl -I -sS -k --connect-timeout "$connect_s" --max-time "$remain_s" \
Review Comment:
Confirmed. Bounding each request bounds the request, not the loop — the pause was a flat `sleep 2` taken before the clock was re-read, so `timeout_s=1` ran for about 2s. I had noted the overshoot in a `TODO(wait_for_startup)` and left it; you are right that documenting it is not the same as honouring the timeout. Fixed in `d93b6f9d`:
```bash
now_s=$(date '+%s')
local sleep_s=$((stop_s - now_s))
[ "$sleep_s" -le 0 ] && break
[ "$sleep_s" -gt 2 ] && sleep_s=2
sleep "$sleep_s"
now_s=$(date '+%s')
```
The `break` matters as much as the cap: with the deadline spent, falling through to the `while` guard on a whole-second clock would spin on repeated instant probes until the second ticked over.
On the assertion — you asked for elapsed time, and the suite now checks it, but the load-bearing check is the other one. Wall-clock at `date +%s` resolution cannot separate a 1s run from a 2s run reliably, so both are asserted: `sleep` is shimmed to record what was requested and then take it for real, so the duration stays a real measurement.
```
PASS retry sleeps stay inside the 1s deadline
PASS wait_for_startup returns within the deadline (1s)
```
Total requested sleep must be `<= timeout_s`, which is exact — restoring `sleep 2` fails it every time, while the elapsed check alone would be a coin flip on the second boundary. Ran it five times, 1s each time.
`wait_for_shutdown` has the same fixed-pause-then-check shape and the same overrun. Left alone with a `TODO(wait_for_shutdown)` pointing at this fix, since it is untouched by this PR and widening the diff is the thing you asked me not to do. Happy to fix it here if you would rather.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5056128517
@copilot review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3647172029
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,92 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Extract host
+ if [[ "$url" =~ \[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ local linux_pattern
+ local bsd_pattern
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ linux_pattern=":${port}([[:space:]]|$)"
+ bsd_pattern="(\.|:)${port}([[:space:]]|$)"
+ else
+ local esc_host="${host//./\.}"
+ linux_pattern="(0\.0\.0\.0|\*|\[::\]|::|${esc_host}|\[${esc_host}\]):${port}([[:space:]]|$)"
+ bsd_pattern="(0\.0\.0\.0|\*|\[::\]|::|${esc_host})(\.|:)${port}([[:space:]]|$)"
+ fi
+
+ local in_use=0
+ local port_checked=0
+ local out=""
+
+ if command_available "ss"; then
+ if out=$(ss -ltn 2>/dev/null); then
+ port_checked=1
+ if echo "$out" | grep -qE "$linux_pattern"; then
Review Comment:
‼️ `ss -n` and `netstat -n` report numeric addresses, but this pattern compares them with the configured hostname text. `ServerOptionsTest.testUrlNormalizationPreservesHostnameCase` explicitly supports hostnames; with `restserver.url=http://localhost:8080` and `ss` reporting `127.0.0.1:8080`, this branch sets `port_checked=1`, misses the listener, and never reaches the resolving `/dev/tcp` fallback. A controlled run on this head returns success (port free) for that occupied endpoint. Please resolve hostnames to their IPv4/IPv6 addresses before matching, or use a deadline-bounded probe for hostname inputs, and add a hostname-to-numeric-listener regression.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,481 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# test-check-port.sh — Unit tests for check_port() in util.sh
+#
+# Strategy: each test runs check_port in a subshell that overrides
+# command_available() to control which probe branch is taken, and
+# overrides the tool functions (ss, netstat, timeout) to control
+# what they return — no real network connections needed.
+#
+# check_port calls `exit 1` when the port is in use, so the subshell
+# exits 1; it returns normally (exit 0) when the port is free.
+#
+# Usage: ./test-check-port.sh [path-to-hugegraph-static-dir]
+# path-to-hugegraph-static-dir: directory containing bin/util.sh
+# Defaults to current directory.
+# In CI: $TRAVIS_DIR/test-check-port.sh hugegraph-server/hugegraph-dist/src/assembly/static
+
+set -uo pipefail
+
+STATIC_DIR="${1:-$(pwd)}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+REPO_ROOT="$(cd "$(dirname "$0")/../../../../.." && pwd)"
+PD_UTIL_SH="$REPO_ROOT/hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh"
+
+PASS=0
+FAIL=0
+ERRORS=()
+
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+pass() { echo -e "${GREEN} PASS${NC} $1"; PASS=$((PASS + 1)); }
+fail() { echo -e "${RED} FAIL${NC} $1"; ERRORS+=("$1"); FAIL=$((FAIL + 1)); }
+section() { echo ""; echo "── $1 ──"; }
+
+echo ""
+echo "check_port() unit test suite"
+echo "util.sh: $UTIL_SH"
+echo ""
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo -e "${RED}ERROR:${NC} $UTIL_SH not found."
+ echo " Pass the HugeGraph static assembly dir as \$1"
+ exit 1
+fi
+
+# ── ss branch ─────────────────────────────────────────────────────────────────
+
+section "ss branch — IPv4"
+
+(
+ # shellcheck source=/dev/null
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: IPv4 port occupied → exit 1" \
+ || fail "ss: IPv4 port occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:9090 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: IPv4 port free → exit 0" \
+ || fail "ss: IPv4 port free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL with scheme (http://[::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: http://[::1]:8080 occupied → exit 1" \
+ || fail "ss: http://[::1]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: http://[::1]:8080 free → exit 0" \
+ || fail "ss: http://[::1]:8080 free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL without scheme ([::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::1]:8080 (no scheme) occupied → exit 1" \
+ || fail "ss: [::1]:8080 (no scheme) occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::1]:8080 (no scheme) free → exit 0" \
+ || fail "ss: [::1]:8080 (no scheme) free → expected exit 0, got 1"
+
+section "ss branch — wildcard 0.0.0.0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://0.0.0.0:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: 0.0.0.0:8080 occupied → exit 1" \
+ || fail "ss: 0.0.0.0:8080 occupied → expected exit 1, got 0"
+
+section "ss branch — wildcard ::"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::]:8080 occupied → exit 1" \
+ || fail "ss: [::]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::]:8080 free → exit 0" \
+ || fail "ss: [::]:8080 free → expected exit 0, got 1"
+
+# ── netstat branch ────────────────────────────────────────────────────────────
+
+section "netstat branch — Linux format (-ltn), occupied"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -ltn: port 8080 occupied → exit 1" \
+ || fail "netstat -ltn: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — Linux format (-ltn), free"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat -ltn: port 8080 free → exit 0" \
+ || fail "netstat -ltn: port 8080 free → expected exit 0, got 1"
+
+section "netstat branch — BSD/macOS fallback (-an), occupied"
+
+# Simulate netstat that produces no output for -ltn (Linux flag unsupported)
+# but outputs BSD-format lines for -an
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() {
+ if [[ "$1" == "-ltn" ]]; then
+ return 1 # flag not supported on BSD
+ fi
+ echo "tcp4 0 0 *.8080 *.* LISTEN"
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -an BSD: port 8080 occupied → exit 1" \
+ || fail "netstat -an BSD: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — IP octet false-positive guard"
+
+# Port 80 check; netstat output contains 192.168.80.1:443
+# The .80 in the IP address must NOT match port 80
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 192.168.80.1:443 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:80"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat: IP octet .80 does not false-positive for port 80 → exit 0" \
+ || fail "netstat: IP octet .80 false-positived for port 80 → expected exit 0, got 1"
+
+# ── /dev/tcp fallback branch ──────────────────────────────────────────────────
+
+section "/dev/tcp fallback — timeout available, port occupied"
+
+# timeout exits 0 → connection succeeded → port in use
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ # Assert correct invocation: timeout 1 bash -c SCRIPT _ HOST PORT
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 0
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "/dev/tcp+timeout: connection succeeded (exit 0) → port occupied → exit 1" \
+ || fail "/dev/tcp+timeout: connection succeeded → expected exit 1, got 0"
+
+section "/dev/tcp fallback — timeout available, port free"
+
+# timeout exits 1 → connection refused → port free
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 1
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "/dev/tcp+timeout: connection refused (exit 1) → port free → exit 0" \
+ || fail "/dev/tcp+timeout: connection refused → expected exit 0, got 1"
+
+section "/dev/tcp fallback — real loopback (no mock)"
+
+(
+ if ! command -v python3 >/dev/null 2>&1; then
+ echo "SKIP: python3 not available — skipping real loopback test"
+ exit 77
+ fi
+
+ source "$UTIL_SH"
+ # Force the fallback by pretending ss/netstat don't exist
+ command_available() {
+ if [[ "$1" == "ss" || "$1" == "netstat" ]]; then return 1; fi
+ command -v "$1" >/dev/null 2>&1
+ }
+ # Start a real listener on an ephemeral high port (e.g., 54321)
+ # Use python as a simple cross-platform web server since nc arguments vary
+ python3 -m http.server 54321 --bind 127.0.0.1 >/dev/null 2>&1 &
+ PY_PID=$!
+ trap "kill -9 $PY_PID 2>/dev/null || true" EXIT
+ sleep 1 # wait for it to bind
Review Comment:
⚠️ This is a fixed port, not an ephemeral one, and the test never verifies that the Python child actually bound it. If 54321 is already occupied, Python exits immediately, `check_port` connects to the unrelated listener, and the test still passes. Please bind port 0 and return the selected port to the test (or at least assert child liveness/readiness before calling `check_port`) so this cannot produce a false-positive green result.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5073820377
fixing remaining issues
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3650486632
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,245 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# Run a command with a hard deadline via background watchdog.
+# Returns the command's exit code if it finishes in time.
+# If the deadline expires, the command is killed (exit code reflects signal).
+# Works without the timeout command — uses sleep + kill -9 pattern.
+function run_with_deadline() {
+ local cmd="$1"
+ local deadline="$2"
+ shift 2
+
+ bash -c "$cmd" bash "$@" &
+ local child_pid=$!
+ (
+ sleep "$deadline"
+ kill -9 "$child_pid" 2>/dev/null
+ ) 2>/dev/null &
+ local watchdog_pid=$!
+
+ wait "$child_pid" 2>/dev/null
+ local rc=$?
+ kill -9 "$watchdog_pid" 2>/dev/null || true
+ wait "$watchdog_pid" 2>/dev/null || true
+ return $rc
+}
+
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Strip leading/trailing whitespace from URL (handles whitespace from ServerOptions)
+ url="${url#"${url%%[![:space:]]*}"}"
+ url="${url%"${url##*[![:space:]]}"}"
+
+ # Extract authority: strip scheme (http://, https://, or none) and path.
+ # This ensures port is extracted from host:port, not from a colon in the path.
+ local authority
+ if [[ "$url" =~ ^[a-zA-Z][a-zA-Z0-9+.-]*:// ]]; then
+ authority=$(echo "$url" | sed 's|^[^/]*://||; s|/.*||')
+ else
+ authority=$(echo "$url" | sed 's|/.*||')
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host and port from authority.
+ # Assumes IPv6 is bracketed (e.g. [::1]:8080). Unbracketed IPv6 like
+ # ::1:8080 would misparse as host=::, port=1. ServerOptions does not
+ # enforce bracketing at the config layer; if this ever fires on bad input
+ # the downstream bind would fail with a clearer error than the preflight.
+ if [[ "$authority" =~ ^\[([^\]]*)\]:([0-9]+)$ ]]; then
+ # IPv6 with port: [::1]:8080
+ host="${BASH_REMATCH[1]}"
+ port="${BASH_REMATCH[2]}"
+ elif [[ "$authority" =~ :([0-9]+)$ ]]; then
+ # IPv4 or hostname with port: 127.0.0.1:8080
+ port="${BASH_REMATCH[1]}"
+ host="${authority%:*}"
+ else
+ # No explicit port in authority
+ host="$authority"
+ port=""
+ fi
+
+ # Handle default ports from scheme when no explicit port given
+ if [[ -z "$port" ]]; then
+ # Reject invalid port: authority has exactly one colon (host:non-digits).
+ # IPv6 addresses (2+ colons, e.g. [::1] or ::1) are not caught by this.
+ if [[ "$authority" != *:*:* && "$authority" == *:* ]]; then
+ return 0
+ fi
+ if [[ "$url" == https://* ]]; then
+ port="443"
+ elif [[ "$url" == http://* ]]; then
+ port="80"
+ fi
+ fi
+
+ if [[ -z "$port" ]]; then
+ return 0
+ fi
+
+ if ! [[ "$port" =~ ^[0-9]+$ ]]; then
+ return 0
+ fi
+ port=$((10#$port))
+ if (( port < 1 || port > 65535 )); then
+ return 0
+ fi
+
+ # Strip any leading/trailing whitespace from host
+ host="${host#"${host%%[![:space:]]*}"}"
+ host="${host%"${host##*[![:space:]]}"}"
+
+ # Resolve hostname → numeric IPs so ss/netstat (which use -n) can match them.
+ # A "hostname" is anything that is not blank, a wildcard, or already numeric.
+ # Resolution runs with a deadline to prevent hangs from slow/stuck DNS/LDAP.
+ # If timeout is unavailable, skip resolution and fall through to bounded /dev/tcp.
+ local resolved_addrs=""
+ local is_hostname=0
+ if [[ -n "$host" && "$host" != "0.0.0.0" && "$host" != "::" && "$host" != "*" ]] \
+ && ! [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] \
+ && ! [[ "$host" =~ ^[0-9a-fA-F:]*:[0-9a-fA-F:]*$ ]]; then
+ is_hostname=1
+ if command_available "getent" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 getent hosts "$host" 2>/dev/null | awk '{print $1}')
+ elif command_available "dscacheutil" && command_available "timeout"; then
+ resolved_addrs=$(timeout 2 dscacheutil -q host -a name "$host" 2>/dev/null \
+ | awk '/ip_address:/{print $2}')
+ fi
+ # If timeout unavailable or resolution times out, resolved_addrs stays empty
+ # and we fall through to the bounded /dev/tcp probe (2s watchdog) instead.
+ fi
+
+ local linux_pattern
+ local bsd_pattern
+ if [[ -z "$host" || "$host" == "0.0.0.0" || "$host" == "::" || "$host" == "*" ]]; then
+ # Wildcard patterns match any address family (IPv4 or IPv6) on the port
+ # Note: This treats IPv4 and IPv6 wildcard listeners as conflicts, which is conservative
+ # but may be overly strict for dual-stack systems where they can coexist
+ linux_pattern=":${port}([[:space:]]|$)"
+ bsd_pattern="(\.|:)${port}([[:space:]]|$)"
+ else
+ # For hostnames, only use resolved numeric addresses (ss/netstat report numeric).
+ # Keep wildcard matching family-aware to avoid cross-family false conflicts.
+ local addr_alts=""
+ local match_ipv4=0
+ local match_ipv6=0
+ if [[ $is_hostname -eq 1 ]]; then
+ # Hostname: use resolved addresses and infer address family set
+ while IFS= read -r addr; do
+ [[ -z "$addr" ]] && continue
+ local esc_addr="${addr//./\\.}"
+ if [[ "$addr" == *":"* ]]; then
+ esc_addr="${esc_addr//:/\\:}"
+ match_ipv6=1
+ else
+ match_ipv4=1
+ fi
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="${esc_addr}|\[${esc_addr}\]"
+ else
+ addr_alts="${addr_alts}|${esc_addr}|\[${esc_addr}\]"
+ fi
+ done <<< "$resolved_addrs"
+ else
+ # Numeric address: use it directly and infer address family
+ local esc_host="${host//./\\.}"
+ if [[ "$host" == *":"* ]]; then
+ esc_host="${esc_host//:/\\:}"
+ match_ipv6=1
+ else
+ match_ipv4=1
+ fi
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="${esc_host}|\[${esc_host}\]"
+ else
+ addr_alts="${addr_alts}|${esc_host}|\[${esc_host}\]"
+ fi
+ fi
+ if [[ $match_ipv4 -eq 1 ]]; then
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="0\.0\.0\.0|\*"
+ else
+ addr_alts="${addr_alts}|0\.0\.0\.0|\*"
+ fi
+ fi
+ if [[ $match_ipv6 -eq 1 ]]; then
+ if [[ -z "$addr_alts" ]]; then
+ addr_alts="\[::\]|::"
+ else
+ addr_alts="${addr_alts}|\[::\]|::"
+ fi
+ fi
+ # Pattern: addresses followed by colon and port, with whitespace/end anchor
+ # (avoids IPv6 hextet false positives without GNU-specific \b)
+ linux_pattern="(${addr_alts}):${port}([[:space:]]|$)"
+ bsd_pattern="(${addr_alts})(\\.|:)${port}([[:space:]]|$)"
+ fi
+
+ local in_use=0
+ local port_checked=0
+ local out=""
+
+ if command_available "ss"; then
+ if out=$(ss -ltn 2>/dev/null); then
+ # Only mark as checked if we can actually match the configured endpoint.
+ # For unresolved hostnames, fall through to the /dev/tcp probe instead.
+ if [[ $is_hostname -eq 0 || -n "$resolved_addrs" ]]; then
+ port_checked=1
+ if echo "$out" | grep -qE "$linux_pattern"; then
+ in_use=1
+ fi
+ fi
+ else
+ # ss command failed (tool present but exited non-zero), try next tool
+ port_checked=0
+ fi
+ fi
+
+ if [[ $port_checked -eq 0 ]] && command_available "netstat"; then
+ if out=$(netstat -ltn 2>/dev/null) && echo "$out" | grep -qi "listen"; then
+ if [[ $is_hostname -eq 0 || -n "$resolved_addrs" ]]; then
+ port_checked=1
+ if echo "$out" | grep -qE "$linux_pattern" || echo "$out" | grep -qE "$bsd_pattern"; then
+ in_use=1
+ fi
+ fi
+ elif out=$(netstat -an 2>/dev/null) && [[ -n "$out" ]]; then
+ if [[ $is_hostname -eq 0 || -n "$resolved_addrs" ]]; then
+ port_checked=1
+ if echo "$out" | grep -i "listen" | grep -qE "$bsd_pattern"; then
+ in_use=1
+ fi
+ fi
+ fi
+ fi
+
+ if [[ $port_checked -eq 0 ]]; then
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ local probe_host="$host"
+ if [[ -z "$probe_host" || "$probe_host" == "0.0.0.0" || "$probe_host" == "*" ]]; then
+ probe_host="127.0.0.1"
+ elif [[ "$probe_host" == "::" ]]; then
+ probe_host="::1"
+ fi
+
+ if command_available "timeout"; then
+ if timeout 1 bash -c ': >/dev/tcp/"$1"/"$2"' _ "$probe_host" "$port" 2>/dev/null; then
+ # 1-second deadline prevents hangs on dropped SYN packets or unresponsive hosts
+ in_use=1
+ fi
+ else
+ # Deadline-bounded probe without the timeout command
+ if run_with_deadline ': >/dev/tcp/"$1"/"$2" 2>/dev/null' "$probe_host" "$port" 2; then
Review Comment:
‼️ `run_with_deadline()` expects `(cmd, deadline, args...)`, but this call passes `(cmd, probe_host, port, 2)`. A controlled exact-head invocation showed the child receives `8080|2`, while `sleep "$deadline"` receives the host. On systems without `timeout`, the fallback therefore probes the wrong endpoint and can report an occupied configured port as free. Please call it as `run_with_deadline '...' 2 "$probe_host" "$port"` and cover occupied, refused, and deadline cases through the actual `check_port` branch.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,706 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# test-check-port.sh — Unit tests for check_port() in util.sh
+#
+# Strategy: each test runs check_port in a subshell that overrides
+# command_available() to control which probe branch is taken, and
+# overrides the tool functions (ss, netstat, timeout) to control
+# what they return — no real network connections needed.
+#
+# check_port calls `exit 1` when the port is in use, so the subshell
+# exits 1; it returns normally (exit 0) when the port is free.
+#
+# Usage: ./test-check-port.sh [path-to-hugegraph-static-dir]
+# path-to-hugegraph-static-dir: directory containing bin/util.sh
+# Defaults to current directory.
+# In CI: $TRAVIS_DIR/test-check-port.sh hugegraph-server/hugegraph-dist/src/assembly/static
+
+set -uo pipefail
+# -u: fail on undefined variables (catches typos in test assertions)
+# -o pipefail: pipeline exit status is the last non-zero component
+# shellcheck disable=SC1090,SC1091 # UTIL_SH / PD_UTIL_SH sourced dynamically at runtime
+
+STATIC_DIR="${1:-$(pwd)}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+
+REPO_ROOT="$(cd "$(dirname "$0")/../../../../.." && pwd)"
+PD_UTIL_SH="$REPO_ROOT/hugegraph-pd/hg-pd-dist/src/assembly/static/bin/util.sh"
+STORE_UTIL_SH="$REPO_ROOT/hugegraph-store/hg-store-dist/src/assembly/static/bin/util.sh"
+
+PASS=0
+FAIL=0
+ERRORS=()
+
+GREEN='\033[0;32m'
+RED='\033[0;31m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+pass() { echo -e "${GREEN} PASS${NC} $1"; PASS=$((PASS + 1)); }
+fail() { echo -e "${RED} FAIL${NC} $1"; ERRORS+=("$1"); FAIL=$((FAIL + 1)); }
+section() { echo ""; echo "── $1 ──"; }
+
+echo ""
+echo "check_port() unit test suite"
+echo "util.sh: $UTIL_SH"
+echo ""
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ echo -e "${RED}ERROR:${NC} $UTIL_SH not found."
+ echo " Pass the HugeGraph static assembly dir as \$1"
+ exit 1
+fi
+
+# ── ss branch ─────────────────────────────────────────────────────────────────
+
+section "ss branch — IPv4"
+
+(
+ # shellcheck source=/dev/null
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: IPv4 port occupied → exit 1" \
+ || fail "ss: IPv4 port occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:9090 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: IPv4 port free → exit 0" \
+ || fail "ss: IPv4 port free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL with scheme (http://[::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: http://[::1]:8080 occupied → exit 1" \
+ || fail "ss: http://[::1]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: http://[::1]:8080 free → exit 0" \
+ || fail "ss: http://[::1]:8080 free → expected exit 0, got 1"
+
+section "ss branch — IPv6 URL without scheme ([::1]:8080)"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::1]:8080 (no scheme) occupied → exit 1" \
+ || fail "ss: [::1]:8080 (no scheme) occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "[::1]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::1]:8080 (no scheme) free → exit 0" \
+ || fail "ss: [::1]:8080 (no scheme) free → expected exit 0, got 1"
+
+section "ss branch — wildcard 0.0.0.0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*"; }
+ check_port "http://0.0.0.0:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: 0.0.0.0:8080 occupied → exit 1" \
+ || fail "ss: 0.0.0.0:8080 occupied → expected exit 1, got 0"
+
+section "ss branch — wildcard ::"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:8080 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "ss: [::]:8080 occupied → exit 1" \
+ || fail "ss: [::]:8080 occupied → expected exit 1, got 0"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 [::]:9090 [::]:*"; }
+ check_port "http://[::]:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: [::]:8080 free → exit 0" \
+ || fail "ss: [::]:8080 free → expected exit 0, got 1"
+
+# ── netstat branch ────────────────────────────────────────────────────────────
+
+section "netstat branch — Linux format (-ltn), occupied"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -ltn: port 8080 occupied → exit 1" \
+ || fail "netstat -ltn: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — Linux format (-ltn), free"
+
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat -ltn: port 8080 free → exit 0" \
+ || fail "netstat -ltn: port 8080 free → expected exit 0, got 1"
+
+section "netstat branch — BSD/macOS fallback (-an), occupied"
+
+# Simulate netstat that produces no output for -ltn (Linux flag unsupported)
+# but outputs BSD-format lines for -an
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() {
+ if [[ "$1" == "-ltn" ]]; then
+ return 1 # flag not supported on BSD
+ fi
+ echo "tcp4 0 0 *.8080 *.* LISTEN"
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "netstat -an BSD: port 8080 occupied → exit 1" \
+ || fail "netstat -an BSD: port 8080 occupied → expected exit 1, got 0"
+
+section "netstat branch — IP octet false-positive guard"
+
+# Port 80 check; netstat output contains 192.168.80.1:443
+# The .80 in the IP address must NOT match port 80
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "netstat" ]]; }
+ netstat() { echo "tcp 0 0 192.168.80.1:443 0.0.0.0:* LISTEN"; }
+ check_port "http://127.0.0.1:80"
+)
+[[ $? -eq 0 ]] \
+ && pass "netstat: IP octet .80 does not false-positive for port 80 → exit 0" \
+ || fail "netstat: IP octet .80 false-positived for port 80 → expected exit 0, got 1"
+
+section "ss branch — host dot-escaping guard"
+
+# Host 127.0.0.1 must be matched literally: a listener whose address merely
+# matches the pattern with '.' as a regex wildcard (127a0b0c1) must NOT count
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "ss" ]]; }
+ ss() { echo "tcp LISTEN 0 128 127a0b0c1:8080 0.0.0.0:*"; }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "ss: unescaped-dot lookalike 127a0b0c1 does not false-positive → exit 0" \
+ || fail "ss: unescaped-dot lookalike 127a0b0c1 false-positived → expected exit 0, got 1"
+
+# ── /dev/tcp fallback branch ──────────────────────────────────────────────────
+
+section "/dev/tcp fallback — timeout available, port occupied"
+
+# timeout exits 0 → connection succeeded → port in use
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ # Assert correct invocation: timeout 1 bash -c SCRIPT _ HOST PORT
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 0
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 1 ]] \
+ && pass "/dev/tcp+timeout: connection succeeded (exit 0) → port occupied → exit 1" \
+ || fail "/dev/tcp+timeout: connection succeeded → expected exit 1, got 0"
+
+section "/dev/tcp fallback — timeout available, port free"
+
+# timeout exits 1 → connection refused → port free
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*"; return 2; }
+ return 1
+ }
+ check_port "http://127.0.0.1:8080"
+)
+[[ $? -eq 0 ]] \
+ && pass "/dev/tcp+timeout: connection refused (exit 1) → port free → exit 0" \
+ || fail "/dev/tcp+timeout: connection refused → expected exit 0, got 1"
+
+section "/dev/tcp fallback — real loopback (ephemeral port)"
+
+# Start Python server on ephemeral port 0, capture actual port from child stdout
+(
+ source "$UTIL_SH"
+ command_available() { [[ "$1" == "timeout" ]]; }
+ # Mock timeout: on hosts without timeout (macOS), run the probe directly.
+ # The probe args are: timeout 1 bash -c SCRIPT _ HOST PORT
+ timeout() {
+ [[ "$1" == "1" && "$2" == "bash" && "$3" == "-c" && "$5" == "_" ]] \
+ || { echo "timeout mock: unexpected argv: $*" >&2; return 2; }
+ # Run the probe with a 2-second hard deadline via background + watchdog
+ bash -c "$4" "$5" "$6" "$7" 2>/dev/null &
+ local probe_pid=$!
+ (sleep 2; kill -9 "$probe_pid" 2>/dev/null) &
+ local watchdog_pid=$!
+ wait "$probe_pid" 2>/dev/null
+ local rc=$?
+ kill -9 "$watchdog_pid" 2>/dev/null
+ wait "$watchdog_pid" 2>/dev/null
+ return $rc
+ }
+ # Use a temp file to capture the bound port from child
+ port_file=$(mktemp)
+
+ # Start Python server that prints the bound port to stdout
+ python3 -c "
+import socket
+s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+s.bind(('127.0.0.1', 0))
+s.listen(1) # actually listen so /dev/tcp can connect
+port = s.getsockname()[1]
+print(port, flush=True)
+import time
+time.sleep(30) # keep server alive
+" > "$port_file" 2>/dev/null &
+ PY_PID=$!
+ # Poll for port file up to ~4s (Python cold-start can exceed 0.5s on busy CI)
+ bound_port=""
+ for _ in $(seq 1 40); do
+ bound_port=$(head -1 "$port_file" 2>/dev/null)
+ [[ -n "$bound_port" ]] && break
+ kill -0 $PY_PID 2>/dev/null || break
+ sleep 0.1
+ done
+ if [[ -z "$bound_port" || ! "$bound_port" =~ ^[0-9]+$ ]]; then
+ echo "SKIP: failed to get bound port"
+ kill -9 $PY_PID 2>/dev/null || true
+ exit 77
+ fi
+ # Verify child is alive
+ if ! kill -0 $PY_PID 2>/dev/null; then
+ echo "SKIP: Python child died"
+ exit 77
+ fi
+ # Register cleanup in EXIT trap — check_port calls exit 1 on occupied port,
+ # so cleanup after check_port is unreachable on that path.
+ trap "rm -f $port_file; kill -9 $PY_PID 2>/dev/null; wait $PY_PID 2>/dev/null" EXIT
+ check_port "http://127.0.0.1:$bound_port"
+)
+_rc=$?
+if [[ $_rc -eq 77 ]]; then
+ echo " SKIP /dev/tcp real ephemeral port (setup failed)"
+elif [[ $_rc -eq 1 ]]; then
+ pass "/dev/tcp real ephemeral port → detects occupation → exit 1"
+else
+ fail "/dev/tcp real ephemeral port → expected exit 1, got $_rc"
+fi
+
+section "/dev/tcp fallback — no-timeout watchdog kills stuck probe"
+
+# run_with_deadline "sleep 5" 2 should return in ~2s, not ~5s.
+# Proves the watchdog actually kills a stuck child, not just that the code path is taken.
+(
+ source "$UTIL_SH"
+ local start=$(date +%s)
Review Comment:
⚠️ `local` is only valid inside a function, but lines 358, 360, and 361 use it directly in a subshell. The exact-head Linux job reports `local: can only be used in a function` and `start: unbound variable`, then fails with 34 passed and 1 failed; the macOS job can false-pass the same errors. Please use ordinary assignments or wrap this assertion in a function, make unexpected shell errors fail the case, and exercise the production no-`timeout` `check_port` path rather than only the helper.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5149786189
Rebased the branch onto the current `master` (`8b2932c7`). Both this PR and the sync PR now point to `09dbc744`; CI has restarted on the rebased head.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3677169573
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,566 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+STORE_UTIL_SH="${2:-}"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ if [[ $# -gt 0 ]]; then
+ echo "ERROR: required util.sh not found at $UTIL_SH" >&2
+ exit 1
+ fi
+ # With no argument this script may be discovered outside the repository by
+ # an optional test runner. CI always supplies STATIC_DIR explicitly, so a
+ # bad workflow path takes the required failure branch above.
+ echo "SKIP: default util.sh not found at $UTIL_SH"
+ exit 0
+fi
+
+if [[ -n "$STORE_UTIL_SH" && ! -f "$STORE_UTIL_SH" ]]; then
+ echo "ERROR: required Store util.sh not found at $STORE_UTIL_SH" >&2
+ exit 1
+fi
+
+# shellcheck source=/dev/null
+source "$UTIL_SH"
+
+# Sections run in subshells so their command overrides stay isolated, which
+# means results have to be tallied through a file rather than a variable.
+RESULTS=$(mktemp)
+# Clean the tally on any exit, not only the normal one. Section 5 runs outside
+# a subshell and has to extend this trap, so it restores this handler rather
+# than clearing it.
+trap 'rm -f "$RESULTS"' EXIT
+
+pass() {
+ echo " PASS $1"
+ echo "P" >> "$RESULTS"
+}
+
+fail() {
+ echo " FAIL $1"
+ echo " $2"
+ echo "F" >> "$RESULTS"
+}
+
+expect() {
+ # expect <name> <expected> <actual>
+ if [[ "$2" == "$3" ]]; then
+ pass "$1"
+ else
+ fail "$1" "expected '$2', got '$3'"
+ fi
+}
+
+echo ""
+echo "check_port contract tests ($UTIL_SH)"
+
+# --------------------------------------------------------------------------
+echo ""
+echo "1. URL to port"
+# "<url>|<expected>", where SKIP means "no usable port, preflight is skipped".
+url_cases=(
+ 'http://127.0.0.1:8080|8080'
+ 'HTTP://127.0.0.1:8080|8080'
+ 'http://127.0.0.1|80'
+ 'https://127.0.0.1|443'
+ '127.0.0.1:8080|8080'
+ 'http://127.0.0.1:8080/path:9090|8080'
+ 'http://127.0.0.1:8080?probe=x|8080'
+ 'http://127.0.0.1:8080#frag|8080'
+ 'http://user:pass@127.0.0.1:8080|8080'
+ 'http://user@127.0.0.1:8080|8080'
+ 'http://[::1]:8080|8080'
+ 'http://user:pass@[::1]:8080|8080'
+ '[::1]:8080|8080'
+ 'https://[::1]|443'
+ 'http://127.0.0.1:08080|8080'
+ '::1:8080|SKIP'
+ 'http://127.0.0.1:abc|SKIP'
+ 'http://127.0.0.1:0|SKIP'
+ 'http://127.0.0.1:70000|SKIP'
+ '127.0.0.1|SKIP'
+ # Oversized values must be rejected on their digits, not after a 64-bit
+ # arithmetic conversion that would wrap them back into range.
+ 'http://127.0.0.1:18446744073709551617|SKIP'
+ 'http://127.0.0.1:18446744073709559616|SKIP'
+ 'http://127.0.0.1:0000000000000008080|8080'
+ 'http://127.0.0.1:00000|SKIP'
+)
+for case in "${url_cases[@]}"; do
+ url="${case%|*}"
+ want="${case##*|}"
+ got=$(parse_port_from_url " $url " 2>/dev/null) || got="SKIP"
+ expect "$url" "$want" "$got"
+done
+
+# --------------------------------------------------------------------------
+echo ""
+echo "2. Linux: ss busy / free / failure, and the netstat fallback"
+(
+ uname() { echo "Linux"; }
+ command_available() { [[ "$1" == "ss" ]]; }
+ SS_OUT=""
+ SS_RC=0
+ ss() { printf '%s' "$SS_OUT"; return "$SS_RC"; }
Review Comment:
⚠️ Make the `ss` mock enforce the production filter. It ignores all argv, while `port_listen_state()` deliberately sets `want_listen=0` and depends on `ss -H -ltn` to exclude `ESTABLISHED`/`TIME_WAIT` rows. Removing `-l` would make a local ephemeral port look busy, yet every mock case and the real-listener case could still pass. Please assert the exact `-H -ltn` arguments and add a non-LISTEN Linux row regression.
##########
hugegraph-server/hugegraph-dist/src/assembly/travis/test-check-port.sh:
##########
@@ -0,0 +1,566 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# Contract tests for the startup port preflight in bin/util.sh.
+#
+# The preflight is best effort: the server's own bind is authoritative. These
+# tests pin the three-state contract (busy / free / unknown) rather than the
+# internals of any one probe.
+#
+# TODO(test-check-port): the Linux and BSD detection branches are both driven
+# by mocked tool output, so on any one runner only the host's own branch is
+# ever exercised against a real kernel. The single real-listener case covers
+# whichever OS the job runs on. Closing this needs the suite to run on both
+# a Linux and a macOS runner, which CI already does for the server job.
+
+set -u
+
+STATIC_DIR="${1:-hugegraph-server/hugegraph-dist/src/assembly/static}"
+UTIL_SH="$STATIC_DIR/bin/util.sh"
+STORE_UTIL_SH="${2:-}"
+
+if [[ ! -f "$UTIL_SH" ]]; then
+ if [[ $# -gt 0 ]]; then
+ echo "ERROR: required util.sh not found at $UTIL_SH" >&2
+ exit 1
+ fi
+ # With no argument this script may be discovered outside the repository by
+ # an optional test runner. CI always supplies STATIC_DIR explicitly, so a
+ # bad workflow path takes the required failure branch above.
+ echo "SKIP: default util.sh not found at $UTIL_SH"
+ exit 0
+fi
+
+if [[ -n "$STORE_UTIL_SH" && ! -f "$STORE_UTIL_SH" ]]; then
+ echo "ERROR: required Store util.sh not found at $STORE_UTIL_SH" >&2
+ exit 1
+fi
+
+# shellcheck source=/dev/null
+source "$UTIL_SH"
+
+# Sections run in subshells so their command overrides stay isolated, which
+# means results have to be tallied through a file rather than a variable.
+RESULTS=$(mktemp)
+# Clean the tally on any exit, not only the normal one. Section 5 runs outside
+# a subshell and has to extend this trap, so it restores this handler rather
+# than clearing it.
+trap 'rm -f "$RESULTS"' EXIT
+
+pass() {
+ echo " PASS $1"
+ echo "P" >> "$RESULTS"
+}
+
+fail() {
+ echo " FAIL $1"
+ echo " $2"
+ echo "F" >> "$RESULTS"
+}
+
+expect() {
+ # expect <name> <expected> <actual>
+ if [[ "$2" == "$3" ]]; then
+ pass "$1"
+ else
+ fail "$1" "expected '$2', got '$3'"
+ fi
+}
+
+echo ""
+echo "check_port contract tests ($UTIL_SH)"
+
+# --------------------------------------------------------------------------
+echo ""
+echo "1. URL to port"
+# "<url>|<expected>", where SKIP means "no usable port, preflight is skipped".
+url_cases=(
+ 'http://127.0.0.1:8080|8080'
+ 'HTTP://127.0.0.1:8080|8080'
+ 'http://127.0.0.1|80'
+ 'https://127.0.0.1|443'
+ '127.0.0.1:8080|8080'
+ 'http://127.0.0.1:8080/path:9090|8080'
+ 'http://127.0.0.1:8080?probe=x|8080'
+ 'http://127.0.0.1:8080#frag|8080'
+ 'http://user:pass@127.0.0.1:8080|8080'
+ 'http://user@127.0.0.1:8080|8080'
+ 'http://[::1]:8080|8080'
+ 'http://user:pass@[::1]:8080|8080'
+ '[::1]:8080|8080'
+ 'https://[::1]|443'
+ 'http://127.0.0.1:08080|8080'
+ '::1:8080|SKIP'
+ 'http://127.0.0.1:abc|SKIP'
+ 'http://127.0.0.1:0|SKIP'
+ 'http://127.0.0.1:70000|SKIP'
+ '127.0.0.1|SKIP'
+ # Oversized values must be rejected on their digits, not after a 64-bit
+ # arithmetic conversion that would wrap them back into range.
+ 'http://127.0.0.1:18446744073709551617|SKIP'
+ 'http://127.0.0.1:18446744073709559616|SKIP'
+ 'http://127.0.0.1:0000000000000008080|8080'
+ 'http://127.0.0.1:00000|SKIP'
+)
+for case in "${url_cases[@]}"; do
+ url="${case%|*}"
+ want="${case##*|}"
+ got=$(parse_port_from_url " $url " 2>/dev/null) || got="SKIP"
+ expect "$url" "$want" "$got"
+done
+
+# --------------------------------------------------------------------------
+echo ""
+echo "2. Linux: ss busy / free / failure, and the netstat fallback"
+(
+ uname() { echo "Linux"; }
+ command_available() { [[ "$1" == "ss" ]]; }
+ SS_OUT=""
+ SS_RC=0
+ ss() { printf '%s' "$SS_OUT"; return "$SS_RC"; }
+
+ SS_OUT='LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:*'
+ expect "listener on 8080 is busy" "busy" "$(port_listen_state 8080)"
+
+ SS_OUT='LISTEN 0 4096 0.0.0.0:22 0.0.0.0:*'
+ expect "no listener on 8080 is free" "free" "$(port_listen_state 8080)"
+
+ # The port must come from the local-address field, not an IPv6 hextet.
+ SS_OUT='LISTEN 0 128 [2001:db8:8080::1]:9090 [::]:*'
+ expect "IPv6 hextet 8080 is not the port" "free" "$(port_listen_state 8080)"
+
+ SS_OUT='LISTEN 0 128 [::]:8080 [::]:*'
+ expect "IPv6 wildcard listener is busy" "busy" "$(port_listen_state 8080)"
+
+ # A tool that runs but fails proves nothing.
+ SS_OUT=''
+ SS_RC=1
+ expect "ss failure is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # `-H` prints no header, so a zero exit with no output is a positive "this
+ # host has no TCP listeners" - the state a fresh container starts in.
+ SS_RC=0
+ SS_OUT=''
+ expect "ss empty output is free" "free" "$(port_listen_state 8080)"
+
+ # Success with an unusable table proves nothing.
+ SS_OUT='some diagnostic banner'
+ expect "ss unparseable output is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # ...and it must not end the search either: netstat may still have a
+ # readable table. Returning on the first probe left the port "unknown"
+ # even when the fallback could have answered.
+ command_available() { [[ "$1" == "ss" || "$1" == "netstat" ]]; }
+ netstat() {
+ echo 'Active Internet connections (only servers)'
+ echo 'Proto Recv-Q Send-Q Local Address Foreign Address State'
+ echo 'tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN'
+ }
+
+ SS_OUT='some diagnostic banner'
+ expect "unparseable ss falls back to netstat" "busy" "$(port_listen_state 8080)"
+ expect "netstat fallback can also report free" "free" "$(port_listen_state 9999)"
+
+ SS_RC=1
+ SS_OUT=''
+ expect "failed ss falls back to netstat" "busy" "$(port_listen_state 8080)"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "3. macOS/BSD: LISTEN versus ESTABLISHED"
+(
+ uname() { echo "Darwin"; }
+ command_available() { [[ "$1" == "netstat" ]]; }
+ NS_OUT=""
+ netstat() { printf '%s' "$NS_OUT"; }
+
+ NS_OUT='Active Internet connections (including servers)
+Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 *.8080 *.* LISTEN'
+ expect "BSD LISTEN on 8080 is busy" "busy" "$(port_listen_state 8080)"
+
+ # An outbound connection to :443 is not a local listener on 443. This is
+ # the false positive that blocked startup on macOS.
+ NS_OUT='Active Internet connections (including servers)
+Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 192.168.1.3.60320 44.195.16.138.443 ESTABLISHED
+tcp4 0 0 *.22 *.* LISTEN'
+ expect "BSD ESTABLISHED peer :443 is free" "free" "$(port_listen_state 443)"
+
+ # A socket lingering in TIME_WAIT holds the port in its *local* address but
+ # is not a listener, so only the connection state can tell them apart.
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp4 0 0 127.0.0.1.8080 127.0.0.1.51000 TIME_WAIT
+tcp4 0 0 *.22 *.* LISTEN'
+ expect "BSD TIME_WAIT on local 8080 is free" "free" "$(port_listen_state 8080)"
+
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)
+tcp6 0 0 ::1.8080 *.* LISTEN'
+ expect "BSD IPv6 LISTEN is busy" "busy" "$(port_listen_state 8080)"
+
+ NS_OUT='Proto Recv-Q Send-Q Local Address Foreign Address (state)'
+ expect "BSD header only is unknown" "unknown" "$(port_listen_state 8080)"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "4. Unknown never blocks startup"
+(
+ uname() { echo "Linux"; }
+ command_available() { return 1; }
+
+ expect "no probe tool is unknown" "unknown" "$(port_listen_state 8080)"
+
+ # check_port must warn and let the server perform the authoritative bind.
+ err=$( (check_port "http://127.0.0.1:8080") 2>&1 >/dev/null )
+ rc=$?
+ expect "unknown exits 0" "0" "$rc"
+ if [[ "$err" == *"could not determine"* ]]; then
+ pass "unknown warns on stderr"
+ else
+ fail "unknown warns on stderr" "stderr was: $err"
+ fi
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "5. Real listener on an ephemeral port"
+if command -v python3 >/dev/null 2>&1; then
+ PORT_FILE=$(mktemp)
+ # Cover the temp file from the moment it exists, then widen the trap to the
+ # child as soon as there is a pid; registering only after the fork leaves a
+ # window where an interrupt orphans the listener for its full 30s sleep.
+ trap 'rm -f "$PORT_FILE" "$RESULTS"' EXIT
+ python3 -c '
+import socket, sys, time
+s = socket.socket()
+s.bind(("127.0.0.1", 0))
+s.listen(1)
+print(s.getsockname()[1])
+sys.stdout.flush()
+time.sleep(30)
+' > "$PORT_FILE" &
+ PY_PID=$!
+ trap 'kill "$PY_PID" 2>/dev/null; rm -f "$PORT_FILE" "$RESULTS"' EXIT
+
+ BOUND=""
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
+ BOUND=$(head -1 "$PORT_FILE" 2>/dev/null)
+ [[ -n "$BOUND" ]] && break
+ # Whole seconds only: fractional sleep is not POSIX, and this suite runs
+ # with `set -u` but no `-e`, so a busybox sleep would fail silently and
+ # spin all ten iterations instantly.
+ sleep 1
+ done
+
+ if [[ -z "$BOUND" ]] || ! kill -0 "$PY_PID" 2>/dev/null; then
+ fail "listener bound an ephemeral port" "child did not report a port"
+ else
+ pass "listener bound an ephemeral port ($BOUND)"
+ expect "bound port is busy" "busy" "$(port_listen_state "$BOUND")"
+ (check_port "http://127.0.0.1:$BOUND" >/dev/null 2>&1)
+ expect "check_port exits 1 on the bound port" "1" "$?"
+
+ # A port that was bound and released must not read as busy.
+ FREE=$(python3 -c 'import socket
+s = socket.socket()
+s.bind(("127.0.0.1", 0))
+p = s.getsockname()[1]
+s.close()
+print(p)')
+ expect "released port is not busy" "0" "$([[ "$(port_listen_state "$FREE")" == "busy" ]] && echo 1 || echo 0)"
+ fi
+
+ kill "$PY_PID" 2>/dev/null
+ wait "$PY_PID" 2>/dev/null
+ rm -f "$PORT_FILE"
+ # Restore the script-level handler rather than clearing it, so the tally
+ # file stays covered for the remaining sections.
+ trap 'rm -f "$RESULTS"' EXIT
+else
+ echo " SKIP real listener test: python3 not available"
+fi
+
+# --------------------------------------------------------------------------
+echo ""
+echo "6. download() rename failure is reported"
+(
+ WORK=$(mktemp -d)
+ trap 'rm -rf "$WORK"' EXIT
+
+ command_available() { [[ "$1" == "curl" ]]; }
+ curl() {
+ # Write to the -o destination so a temp file exists to rename.
+ local out=""
+ while [[ $# -gt 0 ]]; do
+ [[ "$1" == "-o" ]] && { out="$2"; shift; }
+ shift
+ done
+ echo "payload" > "$out"
+ return 0
+ }
+ # Simulate a rename that fails (read-only target, cross-device, ...).
+ mv() { return 1; }
+
+ if download "$WORK" "https://example.com/pkg.tar.gz"; then
+ fail "download reports rename failure" "download returned 0 after mv failed"
+ else
+ pass "download reports rename failure"
+ fi
+
+ if [[ -e "$WORK/pkg.tar.gz" ]]; then
+ fail "failed rename leaves no destination" "$WORK/pkg.tar.gz exists"
+ else
+ pass "failed rename leaves no destination"
+ fi
+
+ leftover=$(find "$WORK" -name '.pkg.tar.gz.*' 2>/dev/null | wc -l | tr -d ' ')
+ expect "failed rename cleans its temp file" "0" "$leftover"
+
+)
+
+# --------------------------------------------------------------------------
+echo ""
+echo "7. Startup probe is bounded"
+(
+ WORK=$(mktemp -d)
+ cd "$WORK" || exit 1
+ trap 'cd /; rm -rf "$WORK"' EXIT
+
+ ARGS_FILE="$WORK/curl-args"
+ SLEEP_FILE="$WORK/sleep-args"
+ : > "$SLEEP_FILE"
+ curl() { echo "$*" >> "$ARGS_FILE"; echo "000"; return 28; }
+ # Record what the retry pause asks for, but still take it, so the
+ # end-to-end duration below stays a real measurement.
+ sleep() { echo "$1" >> "$SLEEP_FILE"; command sleep "$1"; }
+ process_status() { return 0; }
+ ps() { return 0; }
+
+ TIMEOUT_S=1
+ START_S=$(date '+%s')
+ wait_for_startup "$$" "test-server" "http://127.0.0.1:1" "$TIMEOUT_S" >/dev/null 2>&1
Review Comment:
⚠️ Assert the timeout contract, not only option presence. This call's return code is discarded, and the `curl` mock returns immediately; the checks only grep for the two flag names. A regression to `--max-time 5` under a one-second deadline—or an erroneous success return—would remain green. Capture `wait_for_startup()`'s status, require failure here, and parse the recorded timeout values to prove each is positive and no larger than the remaining deadline.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5055903180
## [Codecov](https://app.codecov.io/gh/apache/hugegraph/pull/3105?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 1.45%. Comparing base ([`89b648a`](https://app.codecov.io/gh/apache/hugegraph/commit/89b648a7f9a7f6c8d202bb199d3c2442d8d511f9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`6395c0c`](https://app.codecov.io/gh/apache/hugegraph/commit/6395c0c45d108e462107bed84e4456bbf546f080?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on master.
> :exclamation: There is a different number of reports uploaded between BASE (89b648a) and HEAD (6395c0c). Click for more details.
>
> <details><summary>HEAD has 3 uploads less than BASE</summary>
>
>| Flag | BASE (89b648a) | HEAD (6395c0c) |
>|------|------|------|
>||4|1|
></details>
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #3105 +/- ##
============================================
- Coverage 37.43% 1.45% -35.99%
+ Complexity 520 21 -499
============================================
Files 808 786 -22
Lines 69581 67079 -2502
Branches 9165 8721 -444
============================================
- Hits 26048 975 -25073
- Misses 40750 66020 +25270
+ Partials 2783 84 -2699
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/hugegraph/pull/3105?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "imbajin (via GitHub)" <gi...@apache.org>.
imbajin commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3640932477
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,60 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ local in_use=0
+ if command_available "ss"; then
+ if ss -ltn 2>/dev/null | grep -qE "(:${port}\b|:${port}$)"; then
+ in_use=1
+ fi
+ elif command_available "netstat"; then
+ if netstat -ltn 2>/dev/null | grep -qE "(:${port}\b|:${port}$)"; then
+ in_use=1
+ elif netstat -an 2>/dev/null | grep -i "listen" | grep -qE "(\.|:)${port}([[:space:]]|$)"; then
+ in_use=1
+ fi
+ else
+ # Wildcard binds include loopback: normalize to loopback for the probe
+ if [[ -z "$host" || "$host" == "0.0.0.0" ]]; then
+ host="127.0.0.1"
+ elif [[ "$host" == "::" ]]; then
+ host="::1"
+ fi
+
+ # Use bash /dev/tcp as a fallback if ss/netstat are missing,
+ # with a short timeout and opening without a newline payload.
+ if command_available "timeout"; then
+ if timeout 1 bash -c ": >/dev/tcp/$host/$port" 2>/dev/null; then
Review Comment:
⚠️ `host` and `port` come directly from `rest-server.properties`, but interpolating them into the code string passed to `bash -c` reparses configuration text as shell syntax. With `ss`/`netstat` absent and `timeout` present, `restserver.url=http://127.0.0.1:1;printf INJECTED` executes the appended command; a controlled run prints `INJECTED` before reporting the port in use. Please validate the port as an integer in `1..65535` and pass both values as positional parameters, for example `bash -c ': >/dev/tcp/"$1"/"$2"' _ "$host" "$port"`, rather than embedding them in the command string.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,60 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
Review Comment:
⚠️ This IPv6 branch requires `://`, although `ServerOptionsTest.testUrlNormalizationEdgeCases` explicitly supports `[::1]:8080`. The shell receives that raw property before Java normalization, falls through here, and parses `host="["`; on systems without `ss`/`netstat`, `/dev/tcp` then probes an invalid host and can miss an occupied port. Please trim and normalize the value consistently with `ServerOptions` (including bracketed IPv6 with an optional scheme), validate the numeric port, and add a `[::1]:8080` regression.
##########
hugegraph-server/hugegraph-dist/src/assembly/static/bin/util.sh:
##########
@@ -79,15 +79,60 @@ function process_id() {
return "$pid"
}
-# check the port of rest server is occupied
+# check whether the REST server port is occupied
function check_port() {
- local port=$(echo "$1" | sed 's|.*:||' | sed 's|/.*||')
- if ! command_available "lsof"; then
- echo "Required lsof but it is unavailable"
- exit 1
+ local url="$1"
+ local host
+ local port
+
+ # Extract port: last colon-delimited segment, strip trailing path
+ port=$(echo "$url" | sed 's|.*:||' | sed 's|/.*||')
+ if [[ -z "$port" ]]; then
+ return 0
fi
- lsof -i :"$port" >/dev/null
- if [ $? -eq 0 ]; then
+
+ # Extract host: handle IPv6 bracket notation e.g. http://[::1]:8080
+ if [[ "$url" =~ ://\[([^\]]*)\] ]]; then
+ host="${BASH_REMATCH[1]}"
+ else
+ host=$(echo "$url" | sed 's|.*://||' | sed 's|:.*||')
+ fi
+
+ local in_use=0
+ if command_available "ss"; then
Review Comment:
⚠️ These new `ss`, GNU/BSD `netstat`, `timeout`, and raw `/dev/tcp` branches have no focused tests, while the only startup script test still requires `lsof` at lines 148-151 and uses it for cleanup at lines 79-82. That suite therefore cannot exercise the central no-lsof contract in the target environment. Please add PATH/mock-driven shell tests for each probe branch, occupied/free IPv4 and IPv6 cases, and timeout behavior, and make the startup test's prerequisite and cleanup lsof-free.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5078236824
All three 5.5/10 items addressed in `1f3f01e`:
1. **netstat -an empty output** — `[[ -n "$out" ]]` guard added. Empty/diagnostic-only output now falls through to /dev/tcp instead of reporting `port_checked=1`.
2. **No watchdog test** — extracted inline watchdog into `run_with_deadline()` helper (positional params, no injection). Added deterministic test: `run_with_deadline "sleep 5" 2` asserts completion in ≤3s. Proves the watchdog actually kills a stuck child.
3. **EXIT trap cleanup** — already addressed in the current head. The trap at line 340 includes `kill -9 $PY_PID; wait $PY_PID` so the Python listener is reaped even when `check_port` calls `exit 1`.
Also fixed a regression from authority parsing: invalid ports like `http://127.0.0.1:abc` were silently falling through to default port 80 instead of being rejected. Added a guard that rejects authority with exactly one colon and no valid numeric port.
35/35 tests pass. Re-requesting review.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5092882079
Thanks for the detailed design in the last review — I took it in full rather than patching around the edges. Current head: `ea81ad76`.
### What changed
`check_port` is rewritten to the minimal design. It now answers one question — *is anything already listening on this port?* — and reports `busy`, `free` or `unknown`, with the bind left authoritative.
- Parse: case-insensitive scheme, explicit/default port, scheme-less value, bracketed IPv6. Ambiguous unbracketed IPv6 is rejected with a warning instead of guessed.
- Detect: `ss -H -ltn` on Linux (falling back to `netstat -ltn`), `netstat -an -p tcp` on BSD — only `LISTEN` rows, only the local-address column, address split on its **last** separator.
- Removed: DNS resolution, address canonicalization, cross-family matching, `/dev/tcp` and its watchdog. `normalize_addr()` and `run_with_deadline()` are gone entirely.
Worth noting this *strengthens* the original goal rather than only preserving it: there is no longer any unbounded call left in the startup path, not merely no `lsof`.
All 12 items from your list are addressed — the resolution table is in the PR description. Items 2, 3, 6 and 8 are resolved by removal rather than by more shell.
### One deviation
You suggested `fuser` as the Linux fallback; I used `netstat` instead. `fuser` cannot distinguish "not found" from "insufficient privileges", so it would collapse `free` and `unknown` into one result and break the tri-state contract. Happy to switch if you would rather have `fuser` there.
### Size
| | Before | Now |
|---|---|---|
| PR vs `master` | +1731 / −189 | +859 / −188 |
| server `util.sh` | 849 | 617 |
| `test-check-port.sh` | 984 | 320 |
The convergence commit itself is +426 / −1297.
### What this gives up
Port-only detection trades away real capability, so rather than leave that implicit I marked each gap in place with a namespaced `TODO`:
- Port-only matching ignores the listener's address, so a listener on `127.0.0.1:8080` reports the port busy even when the server would bind `192.168.1.5:8080`. That is the old `lsof -i :PORT` behaviour and fails safe, but it can refuse a bind that would have succeeded — it is the one limitation here that can block a legitimate start.
- Zero `LISTEN` sockets is indistinguishable from a restricted table; both report `unknown` and warn.
- With neither `ss` nor `netstat` present there is no probe left. A dependency-free fallback would need a bounded connect, which is exactly what was removed — so that one is not a simple follow-up.
`grep -rn "TODO(check_port)"` finds them; the full table is in the description.
### Tests
`test-check-port.sh` is now a compact contract suite (984 → 320 lines): URL-to-port, `ss` busy/free/failure, BSD `LISTEN` vs `ESTABLISHED` vs `TIME_WAIT`, the `unknown` fallback, one real ephemeral listener that asserts the child actually bound, rename failure, and a bounded startup probe. **44 passed, 0 failed.**
I checked it is not vacuous by mutating the implementation — dropping the `LISTEN` filter, downgrading `unknown` to `free`, and reading the foreign-address column each fail the suite. The first mutation initially passed, which is how the `TIME_WAIT` case got added.
Your macOS repro, before and after on this head:
```
37 ESTABLISHED to :443, no listener on 443
before: check_port "http://0.0.0.0:443" -> "The port 443 has already been used", exit 1
after : -> exit 0 (free)
```
Auditing those gaps also turned up a defect worth mentioning: a URL with userinfo (`http://user:pass@host:port`) was caught by the unbracketed-IPv6 check, so it skipped the preflight and printed a misleading warning about bracket notation. Fixed and covered.
### Out of scope
Two findings are deliberately not addressed, with reasons on their threads: the `libjemalloc_aarch64.so` MD5 (pre-existing `master` value; this PR only added quoting) and the mirror-only `cluster-test` failure (identical signature on branches that do not touch this code).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 closed pull request #3105: fix(bin): replace lsof with /dev/tcp in server check_port; remove dea…
URL: https://github.com/apache/hugegraph/pull/3105
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on code in PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#discussion_r3664128766
##########
.github/workflows/server-ci.yml:
##########
@@ -70,17 +70,30 @@ jobs:
run: |
mvn clean compile -U -Dmaven.javadoc.skip=true -ntp
+ - name: Run check_port unit tests
+ if: ${{ env.BACKEND == 'rocksdb' }}
+ run: |
+ # Validates ss/netstat//dev/tcp replacement for lsof
Review Comment:
Right, `/dev/tcp` is left over from an earlier revision that had a bounded-connect fallback; that branch was removed and the comments were not. Fixed in `d93b6f9d`, all three sites:
```
-# Validates ss/netstat//dev/tcp replacement for lsof
+# Validates the ss/netstat port preflight that replaced lsof
-# Note: lsof removed from prerequisites (replaced with ss/netstat//dev/tcp in check_port).
+# Note: lsof removed from prerequisites; check_port now uses ss, falling back
+# to netstat, and warns without blocking when neither can answer.
```
`grep -rn "dev/tcp"` over the tree is now empty.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof port preflight with ss/netstat [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5149766130
Checked the latest head (`7c014c63`) and the final `codecov/project` failure.
This is not a coverage regression in the PR: `codecov/patch` passes and Codecov reports that all modified coverable lines are covered. The project result is incomplete because HEAD has 2 uploaded reports while BASE has 3. In the CI logs, the fork PR has no `CODECOV_TOKEN`, and the Commons, PD, HStore, and Server upload attempts received HTTP 429 rate-limit responses. The v3 uploader then exited successfully, so the GitHub jobs remained green despite those failed uploads.
The branch is still mergeable but is two commits behind current `master`. I verified a local rebase onto `8b2932c7`: it completed without conflicts, preserved the expected combined tree, and passed the focused port suite (65/65), the newly inherited wait-storage suite (5/5), changed-shell syntax checks, workflow YAML parsing, and `git diff --check`.
Recommendation: rebase and update the shared head branch used by this PR and sync PR hugegraph/hugegraph#167. That will rerun CI against the current base. If Codecov hits the tokenless-upload rate limit again, rerun one coverage-producing job after the reported cooldown; no additional coverage test or production-code change is indicated by the current report.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org
Re: [PR] fix(bin): replace lsof with /dev/tcp in server check_port; remove dea… [hugegraph]
Posted by "bitflicker64 (via GitHub)" <gi...@apache.org>.
bitflicker64 commented on PR #3105:
URL: https://github.com/apache/hugegraph/pull/3105#issuecomment-5077313616
Pushed a follow-up addressing the outstanding threads on the current head. Status per open item:
**Fixed:**
- [Endpoint/dual-stack conflict semantics](https://github.com/apache/hugegraph/pull/3105#discussion_r3645160690) — kept as-is intentionally. Treating IPv4/IPv6 wildcard binds as a conflict is conservative (fails safe: blocks startup on a legitimate coexisting bind rather than missing a real conflict). Left the existing code comment explaining the tradeoff; happy to make this dual-stack-aware in a follow-up if you would rather not carry the false-positive risk.
- [`fuser` cleanup remains unenforced](https://github.com/apache/hugegraph/pull/3105#discussion_r3645160703) — this was already addressed in `8307426`: `server-ci.yml` now gates on `fuser` for non-Darwin runners in the preflight step, and `test-start-hugegraph*.sh` warns explicitly when neither `fuser` nor `lsof` is available instead of silently no-opping.
- `download()` missing directory creation on the `wget` path — the earlier fix only covered `curl` (added `mkdir -p` + `basename`). Applied the same guard to the `wget` branch in all three `util.sh` files (server, PD, store) for consistency.
**Documented, not changed:**
- Unbracketed IPv6 (`::1:8080` without brackets) would still misparse in `check_port` authority extraction. Confirmed `ServerOptions`/`HugeConfig` only trims whitespace and prefixes a default scheme — it does not enforce bracket notation, so this is not provably unreachable. Added a comment at the parse site documenting the assumption and the failure mode, so it does not need rediscovering. Low blast radius since it only affects the pre-flight check, not the actual bind.
Re-requesting review on the latest commit — let me know if any of the above needs more than a comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@hugegraph.apache.org
For additional commands, e-mail: issues-help@hugegraph.apache.org