fix(nav): stop on invalid localization and enforce final velocity path

This commit is contained in:
mzx committed 2026-11-22 11:43:13 +08:00
1 parent b772174c1c
commit 28ac7c488e
24 files changed
+1236 -161

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ def yaw(q):
class Driver(Node):
def __init__(self, profile):
super().__init__('field_lio_evaluation_driver', parameter_overrides=[Parameter('use_sim_time', value=True)])
self.publisher = self.create_publisher(Twist, '/model/sentry/cmd_vel', 10)
self.publisher = self.create_publisher(Twist, os.environ.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel'), 10)
self.origin = None
self.pose = None
self.index = 0
+5 -4
View File
@@ -24,7 +24,7 @@ df -h /dev/shm | sed 's/^/ /'
total=$(ls -1 /dev/shm 2>/dev/null | wc -l)
fast=$(ls -1 /dev/shm 2>/dev/null | grep -cE "$SEG_PATTERN")
echo " 文件总数 : $total"
echo " Fast DDS 残留段 : $fast"
echo " Fast DDS 文件数 : $fast(可能属于活跃进程,不能仅凭文件数判定残留)"
if [ "$fast" -gt 0 ]; then
echo " → 前 10 个:"
ls -1 /dev/shm | grep -E "$SEG_PATTERN" | head -10 | sed 's/^/ /'
@@ -99,10 +99,11 @@ echo "=============================================="
echo " 结论"
echo "=============================================="
if [ "$fast" -eq 0 ]; then
echo " ✅ /dev/shm 干净,没有 Fast DDS 残留。"
echo " 如果节点仍然发现不到彼此,问题不在这里 —— 换方案 B(自定义 BT 去掉 Wait)。"
echo " ✅ 未发现匹配的 Fast DDS 共享内存文件。"
echo " 这不能排除 DDS 发现或服务响应异常;UDPv4 下也可能发生。"
echo " 请查看启动日志中的缺失服务、实际 DDS 环境和 Nav2 激活结果,保留 BT 校验与恢复节点。"
else
echo " ⚠️ 发现 $fast 个 Fast DDS 残留段。"
echo " ⚠️ 发现 $fast 个 Fast DDS 文件;有活跃进程时不应当作残留清理。"
if [ "$n_pids" -eq 0 ]; then
if [ "${1:-}" = "--clean" ]; then
echo " → 开始清理…"
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Shared DDS defaults for both launchers; explicit nonempty settings take precedence."""
import argparse
import json
import os
import shlex
KEYS = ('RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'RMW_FASTRTPS_PUBLICATION_MODE',
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER',
'ROS_LOCALHOST_ONLY')
def defaults(environment):
result = dict(environment)
for key, value in (('ROS_DOMAIN_ID', '0'), ('FASTDDS_BUILTIN_TRANSPORTS', 'UDPv4')):
if not result.get(key):
result[key] = value
return result
def describe(environment):
return json.dumps({key: environment.get(key, '<ROS default>') for key in KEYS},
ensure_ascii=False, sort_keys=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--shell', action='store_true')
args = parser.parse_args()
env = defaults(os.environ)
if args.shell:
for name in ('ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS'):
print(f'export {name}={shlex.quote(env[name])}')
else:
print('[DDS] '+describe(env), flush=True)
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""Nav2 domain preflight, discovery-gated startup and bounded readiness check."""
import argparse
import json
import os
import re
import time
from pathlib import Path
import rclpy
from geometry_msgs.msg import PoseStamped
from lifecycle_msgs.srv import GetState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import Log
from rcl_interfaces.srv import GetParameters
from rclpy.utilities import get_rmw_implementation_identifier
from std_srvs.srv import Trigger
from dds_environment import defaults, describe
CONFLICT_SERVICES = {
'lifecycle_manager_nav2': '/lifecycle_manager_nav2/manage_nodes',
'planner_server': '/planner_server/get_state', 'bt_navigator': '/bt_navigator/get_state',
'controller_server': '/controller_server/get_state', 'map_server': '/map_server/get_state',
'amcl': '/amcl/get_state', 'field_localization': '/field_localization/save_map',
}
def path_probe_request():
# Read-only collision query at the map origin; is_valid need not be true.
request = IsPathValid.Request()
request.path.header.frame_id = 'map'
pose = PoseStamped()
pose.header.frame_id = 'map'
pose.pose.orientation.w = 1.0
request.path.poses = [pose]
return request
def ready(managed, states, manager_active, path_responded):
return (bool(managed) and all(states.get(name) == 3 for name in managed)
and manager_active and path_responded)
def failure_details(managed, states, path_discovered, path_responded, errors):
missing = sorted({match for error in errors for match in
re.findall(r'"([^"]+)" (?:action|service) server not available', error)})
return {'managed_node_list_received': bool(managed),
'missing_dependencies': missing,
'not_active': {name: states.get(name, 'response timeout / unavailable')
for name in managed if states.get(name) != 3},
'is_path_valid_discovered': path_discovered,
'is_path_valid_responded': path_responded, 'errors': errors[-8:]}
def preflight(node, duration):
deadline = time.monotonic()+duration
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.1)
# RViz lifecycle clients can share a manager's node name; only actual servers conflict.
conflicts = sorted(name for name, service in CONFLICT_SERVICES.items()
if node.get_servers_info_by_service(service))
if conflicts:
print('[Nav2] 启动拒绝:当前 ROS_DOMAIN_ID='+os.environ['ROS_DOMAIN_ID']+
' 已有导航/定位节点:'+', '.join(conflicts)+
'。请先正常退出旧启动入口,或为独立仿真显式选择其他 ROS_DOMAIN_ID;未终止任何进程。',
flush=True)
return 1
return 0
def complete_endpoint(info):
# Request/reply endpoints must belong to the same participant, not a stale mixed pair.
return (info.endpoint_count == 2 and len(info.endpoint_gids) == 2
and all(len(gid) >= 12 for gid in info.endpoint_gids)
and info.endpoint_gids[0][:12] == info.endpoint_gids[1][:12])
def lifecycle_discovery_gaps(node, managed):
gaps = []
for name in managed:
for service in ('get_state', 'change_state'):
topic = f'/{name}/{service}'
servers = node.get_servers_info_by_service(topic)
clients = node.get_clients_info_by_service(topic)
if not any(info.node_name == name and complete_endpoint(info) for info in servers):
gaps.append(topic+' server')
if not any(info.node_name == 'lifecycle_manager_nav2' and complete_endpoint(info)
for info in clients):
gaps.append(topic+' manager client')
return gaps
def wait_active(node, timeout, activate=False, result_path=None):
started = time.monotonic()
deadline = started+timeout
parameter = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
active = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
path = node.create_client(IsPathValid, '/is_path_valid')
control = node.create_client(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes') if activate else None
startup_future = None
discovery_since = None
discovery_gaps = []
managed = []
states = {}
observed = {}
clients = {}
pending = {}
errors = []
manager_failed = False
failed_at = None
manager_active = False
path_responded = False
path_discovered = False
stable_since = None
last_poll = 0.0
def on_log(message):
nonlocal manager_failed, failed_at
if message.level >= Log.ERROR and ('bt_navigator' in message.name
or 'lifecycle_manager' in message.name):
errors.append(message.name+': '+message.msg)
del errors[:-8]
if 'Failed to bring up all requested nodes' in message.msg:
manager_failed = True
failed_at = time.monotonic()
subscription = node.create_subscription(Log, '/rosout', on_log, 100)
def submit(key, client, request):
if key not in pending and client.service_is_ready():
pending[key] = (client, client.call_async(request), time.monotonic())
def finish(code):
# Let already-sent queries complete before destroying the clients.
until = time.monotonic()+0.5
while (rclpy.ok() and time.monotonic() < until
and any(not future.done() for _, future, _ in pending.values())):
rclpy.spin_once(node, timeout_sec=0.02)
for client, future, _ in pending.values():
if not future.done():
client.remove_pending_request(future)
if result_path is not None:
result_path.write_text(json.dumps({
'passed': code == 0, 'states': states,
'retryable': (code != 0 and not manager_active
and states.get('bt_navigator') in (1, 2)
and time.monotonic()-observed.get('bt_navigator', 0.0) < 2.5),
**failure_details(managed, states, path_discovered, path_responded, errors)},
ensure_ascii=False, indent=2))
return code
print('[Nav2] 等待 Nav2 激活(全部受管节点 ACTIVE、管理器就绪、/is_path_valid 响应)', flush=True)
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.05)
now = time.monotonic()
for key, (client, future, stamp) in list(pending.items()):
if not future.done() and now-stamp < 2:
continue
response = future.result() if future.done() and not future.cancelled() else None
if not future.done():
client.remove_pending_request(future)
del pending[key]
observed[key] = now if response is not None else 0.0
if key == 'parameters':
if response and response.values:
managed = list(response.values[0].string_array_value)
for name in managed:
if name not in clients:
clients[name] = node.create_client(GetState, f'/{name}/get_state')
elif key == 'manager':
manager_active = bool(response and response.success)
elif key == 'path':
# Collision validity is distinct from request/response availability.
path_responded = response is not None
else:
states[key] = response.current_state.id if response else None
if now-last_poll >= 0.5:
last_poll = now
if not managed:
submit('parameters', parameter, GetParameters.Request(names=['node_names']))
submit('manager', active, Trigger.Request())
path_discovered = path.service_is_ready()
# The planner costmap does not run before activation.
if states.get('planner_server') == 3:
submit('path', path, path_probe_request())
for name, client in clients.items():
if not client.service_is_ready() or now-observed.get(name, 0.0) > 2.5:
states[name] = None
submit(name, client, GetState.Request())
if not active.service_is_ready() or now-observed.get('manager', 0.0) > 2.5:
manager_active = False
if not path_discovered or now-observed.get('path', 0.0) > 2.5:
path_responded = False
if activate and startup_future is None:
discovery_gaps = lifecycle_discovery_gaps(node, managed) if managed else ['manager node list']
warmed = (bool(managed) and not discovery_gaps and control.service_is_ready()
and observed.get('manager', 0.0) > 0
and all(states.get(name) == 1 for name in managed))
if warmed:
if discovery_since is None:
discovery_since = now
if now-discovery_since >= 1:
print('[Nav2] 状态服务已响应、管理器状态切换端点完整,发起 STARTUP', flush=True)
startup_future = control.call_async(ManageLifecycleNodes.Request(
command=ManageLifecycleNodes.Request.STARTUP))
else:
discovery_since = None
if startup_future is not None and startup_future.done():
response = startup_future.result()
if response is None or not response.success:
errors.append('lifecycle_manager_nav2: STARTUP returned failure')
manager_failed = True
if failed_at is None:
failed_at = now
if manager_failed:
# Obtain a fresh navigator state after its failed activation callback returns.
# Recovery is permitted only if the navigator is definitely not ACTIVE.
if observed.get('bt_navigator', 0.0) > failed_at or now-failed_at > 2.5:
break
continue
if ready(managed, states, manager_active, path_responded):
if stable_since is None:
stable_since = now
if now-stable_since >= 1:
print(f'[Nav2] Nav2 就绪:{len(managed)} 个受管节点 ACTIVE,'
f'/is_path_valid 已响应,耗时 {now-started:.2f}s', flush=True)
return finish(0)
else:
stable_since = None
_ = subscription
print('[Nav2] 激活失败:'+json.dumps(failure_details(
managed, states, path_discovered, path_responded, errors), ensure_ascii=False), flush=True)
if discovery_gaps and startup_future is None:
print('[Nav2] 尚未完成发现的生命周期端点:'+', '.join(discovery_gaps), flush=True)
return finish(1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preflight', action='store_true')
parser.add_argument('--activate', action='store_true',
help='call manager STARTUP once, after lifecycle discovery is ready (requires autostart=False)')
parser.add_argument('--result', type=Path)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('--discovery-seconds', type=float, default=3)
args = parser.parse_args()
if args.timeout <= 0 or args.discovery_seconds <= 0:
parser.error('timeouts must be positive')
os.environ.update(defaults(os.environ))
print('[DDS] '+describe(os.environ), flush=True)
rclpy.init(args=[])
node = rclpy.create_node('sentry_nav2_preflight' if args.preflight else 'sentry_nav2_readiness')
print('[DDS] actual RMW='+get_rmw_implementation_identifier(), flush=True)
try:
return preflight(node, args.discovery_seconds) if args.preflight else wait_active(
node, args.timeout, args.activate, args.result)
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
raise SystemExit(main())
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Supervise only our Nav2 process group; bounded recovery before navigation becomes active."""
import argparse
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
def stop_owned(process):
if process is None:
return
# Each child is started in a new session. No process-name matching or shared-memory cleanup.
for signum, timeout in ((signal.SIGINT, 8), (signal.SIGTERM, 2), (signal.SIGKILL, 1)):
try:
os.killpg(process.pid, signum)
except ProcessLookupError:
break
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
process.poll()
try:
os.killpg(process.pid, 0)
except ProcessLookupError:
return
time.sleep(0.05)
process.poll()
def supervise(command, checker, attempts, timeout):
navigation = None
observer = None
try:
with tempfile.TemporaryDirectory(prefix='sentry-nav2-') as directory:
for attempt in range(1, attempts+1):
result_path = Path(directory)/f'{attempt}.json'
print(f'[Nav2 supervisor] startup attempt {attempt}/{attempts}', flush=True)
navigation = subprocess.Popen(command, start_new_session=True)
observer = subprocess.Popen(
checker+['--activate', '--timeout', str(timeout), '--result', str(result_path)],
start_new_session=True)
while navigation.poll() is None and observer.poll() is None:
time.sleep(0.1)
if navigation.poll() is not None:
print('[Nav2 supervisor] Nav2 process exited before readiness; aborting', flush=True)
return 1
result = json.loads(result_path.read_text()) if result_path.is_file() else {}
if observer.returncode == 0 and result.get('passed'):
print(f'[Nav2 supervisor] ready on attempt {attempt}; startup recovery disabled', flush=True)
return navigation.wait()
stop_owned(observer)
observer = None
stop_owned(navigation)
navigation = None
if not result.get('retryable') or attempt == attempts:
print('[Nav2 supervisor] startup failed; no further retry (navigator active/unknown, '
'or attempt limit reached)', flush=True)
return 1
print('[Nav2 supervisor] navigator confirmed UNCONFIGURED/INACTIVE; '
'recreating only owned Nav2 processes. LIO/Gazebo continue running.', flush=True)
return 1
finally:
stop_owned(observer)
stop_owned(navigation)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--attempts', type=int, default=3)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('launch_arguments', nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.attempts < 1 or args.attempts > 3 or args.timeout <= 0:
parser.error('attempts must be 1..3; timeout must be positive')
arguments = args.launch_arguments
if arguments and arguments[0] == '--':
arguments = arguments[1:]
if not arguments:
parser.error('Nav2 bringup arguments required after --')
def interrupted(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
raise KeyboardInterrupt
signal.signal(signal.SIGINT, interrupted)
signal.signal(signal.SIGTERM, interrupted)
try:
return supervise(['ros2', 'launch', 'nav2_bringup', 'bringup_launch.py', *arguments],
[sys.executable, str(Path(__file__).with_name('nav2_startup.py'))],
args.attempts, args.timeout)
except KeyboardInterrupt:
return 130
if __name__ == '__main__':
raise SystemExit(main())
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Isolated live relay test. No Gazebo, TF, or real actuator subscribers."""
import argparse
import os
from pathlib import Path
import signal
import subprocess
import time
import uuid
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary',type=Path,default=Path(__file__).resolve().parents[1]/'build/bin/cmd_vel_relay')
args=parser.parse_args()
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
import rclpy
from geometry_msgs.msg import Twist
from std_msgs.msg import Bool
from action_msgs.srv import CancelGoal
rclpy.init();node=rclpy.create_node('test_motion_interlock')
received=[];cancellations=[]
subscription=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda m:received.append((time.monotonic(),m.linear.x)),100)
health=node.create_publisher(Bool,'/field_localization/navigation_valid',1)
final=node.create_publisher(Twist,'/cmd_vel',1)
upstream=node.create_publisher(Twist,'/cmd_vel_smoothed',1)
raw=node.create_publisher(Twist,'/cmd_vel_nav',1)
def cancel(req,response):
cancellations.append(time.monotonic());response.return_code=0
return response
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
for name in ['/navigate_to_pose','/navigate_through_poses']]
process=subprocess.Popen([str(args.binary),'--ros-args','-p','navigation_mode:=true'],
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
checks=0
def check(ok,message):
nonlocal checks
checks+=1
if not ok: raise RuntimeError(message)
print('PASS',message,flush=True)
def drive(duration,valid=True,publish_health=True,publish_final=True):
until=time.monotonic()+duration
while time.monotonic()<until:
if publish_health:
h=Bool();h.data=valid;health.publish(h)
if publish_final:
m=Twist();m.linear.x=0.1;final.publish(m)
m=Twist();m.linear.x=1.5;upstream.publish(m);raw.publish(m)
rclpy.spin_once(node,timeout_sec=0.01)
try:
deadline=time.monotonic()+10
while final.get_subscription_count()<1 and time.monotonic()<deadline:
rclpy.spin_once(node,timeout_sec=0.02)
check(final.get_subscription_count()==1,'one final velocity subscription')
drive(0.5,publish_health=False)
check(received and all(v==0 for _,v in received),'no motion before valid localization')
# A blocked nonzero command requests cancellation; allow both services to acknowledge.
drive(0.8)
check(any(v==0.1 for _,v in received),'valid final velocity reaches actuator')
check(all(v<=0.1 for _,v in received),'raw and smoothed topics cannot bypass collision output')
before=time.monotonic();drive(0.4,valid=False)
zeros=[t for t,v in received if t>=before and v==0]
check(bool(zeros) and min(zeros)-before<0.1,'invalid health stops within 100 ms')
check(len(cancellations)>=2,'navigation action servers receive cancellation')
drive(0.5)
before=time.monotonic();drive(0.6,publish_health=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale health stops within 400 ms')
drive(0.5)
before=time.monotonic();drive(0.6,publish_final=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale final command stops despite upstream traffic')
check(process.poll() is None,'relay remains alive')
print(f'{checks} live checks passed; health_stop_ms={(min(t for t,v in received if t>=before+0.3 and v==0)-before)*1000:.3f}')
finally:
if process.poll() is None:os.killpg(process.pid,signal.SIGINT)
try:process.wait(timeout=5)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
_=subscription,services
node.destroy_node();rclpy.shutdown()
if __name__=='__main__':main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Fault-injection checks using isolated ROS services, without Gazebo or motion commands."""
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
from types import SimpleNamespace
from dds_environment import defaults
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
env = defaults({'ROS_DOMAIN_ID': '77', 'FASTDDS_BUILTIN_TRANSPORTS': 'SHM'})
CHECK(env['ROS_DOMAIN_ID'] == '77' and env['FASTDDS_BUILTIN_TRANSPORTS'] == 'SHM',
'explicit environment override lost')
os.environ.update(defaults(os.environ))
os.environ['ROS_DOMAIN_ID'] = str(50+int(uuid.uuid4().hex[:8], 16) % 50)
import rclpy
from lifecycle_msgs.msg import State
from lifecycle_msgs.srv import GetState, ChangeState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import ParameterValue, ParameterType
from rcl_interfaces.srv import GetParameters
from std_srvs.srv import Trigger
from nav2_startup import ready, failure_details, complete_endpoint
managed = ['planner_server', 'bt_navigator', 'waypoint_follower']
states = dict.fromkeys(managed, 3)
CHECK(ready(managed, states, True, True), 'valid readiness rejected')
CHECK(not ready([], {}, True, True), 'missing manager node list accepted')
CHECK(not ready(managed, {**states, 'bt_navigator': 2}, True, True), 'inactive node accepted')
CHECK(not ready(managed, states, False, True), 'manager incomplete accepted')
CHECK(not ready(managed, states, True, False), 'nonresponding path service accepted')
details = failure_details(managed, {}, True, False,
['"wait" action server not available after waiting for 60.00s'])
CHECK(details['missing_dependencies'] == ['wait'], 'missing action not identified')
CHECK(complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [0]*16])),
'complete endpoint pair rejected')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [1]*16])),
'stale endpoints from different participants accepted')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=1, endpoint_gids=[[0]*16])),
'half-discovered service accepted')
rclpy.init()
node = rclpy.create_node('planner_server')
executor = rclpy.executors.SingleThreadedExecutor()
executor.add_node(node)
extra_nodes = []
state_id = [3]
starts = []
def parameters(request, response):
response.values = [ParameterValue(type=ParameterType.PARAMETER_STRING_ARRAY,
string_array_value=managed)]
return response
def active(request, response):
response.success = True
return response
def state(request, response):
response.current_state = State(id=state_id[0])
return response
services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters),
node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)]
services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed]
command = [sys.executable, str(Path(__file__).with_name('nav2_startup.py'))]
def run(arguments):
process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, start_new_session=True)
try:
deadline = time.monotonic()+15
while process.poll() is None and time.monotonic() < deadline:
executor.spin_once(timeout_sec=0.02)
if process.poll() is None:
raise RuntimeError('test subprocess did not finish')
return process.returncode, process.communicate()[0]
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
try:
code, text = run(['--preflight', '--discovery-seconds', '1'])
CHECK(code == 1 and 'planner_server' in text and '启动拒绝' in text,
'occupied domain was not rejected: '+text)
code, text = run(['--timeout', '3'])
CHECK(code == 1 and '激活失败' in text and '"is_path_valid_responded": false' in text,
'all active nodes with missing path service incorrectly reported ready: '+text)
def path(request, response):
response.success = True
response.is_valid = False # A collision result must not be confused with transport failure.
return response
services.append(node.create_service(IsPathValid, '/is_path_valid', path))
code, text = run(['--timeout', '8'])
CHECK(code == 0 and 'Nav2 就绪' in text, 'responsive service not accepted: '+text)
def startup(request, response):
starts.append(request.command)
state_id[0] = 3
response.success = True
return response
services.append(node.create_service(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes', startup))
state_id[0] = 1
code, text = run(['--activate', '--timeout', '3'])
CHECK(code == 1 and not starts, 'STARTUP issued before lifecycle discovery was complete: '+text)
# Give each lifecycle server its actual node name, and create the manager's clients.
for service in services[2:5]:
node.destroy_service(service)
owners = [node]
for name in managed[1:]:
owner = rclpy.create_node(name)
extra_nodes.append(owner)
executor.add_node(owner)
owners.append(owner)
manager = rclpy.create_node('lifecycle_manager_nav2', start_parameter_services=False)
extra_nodes.append(manager)
executor.add_node(manager)
manager_clients = []
for name, owner in zip(managed, owners):
services.append(owner.create_service(GetState, f'/{name}/get_state', state))
services.append(owner.create_service(ChangeState, f'/{name}/change_state', lambda req, res: res))
manager_clients += [manager.create_client(GetState, f'/{name}/get_state'),
manager.create_client(ChangeState, f'/{name}/change_state')]
code, text = run(['--activate', '--timeout', '10'])
CHECK(code == 0 and starts == [ManageLifecycleNodes.Request.STARTUP] and 'Nav2 就绪' in text,
'gated STARTUP did not occur exactly once: '+text)
print('PASS: 15 checks including partial/stale discovery, startup gating, occupied domain, missing service, and readiness')
finally:
executor.shutdown()
for other in extra_nodes:
other.destroy_node()
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Exercise startup retry limits and process ownership without ROS or Gazebo."""
from pathlib import Path
import subprocess
import sys
import tempfile
from run_nav2 import stop_owned, supervise
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
with tempfile.TemporaryDirectory(prefix='nav2-supervisor-test-') as directory:
root = Path(directory)
navigation = root/'navigation.py'
navigation.write_text('''import signal,sys,time
signal.signal(signal.SIGINT, lambda *args: sys.exit(0))
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
time.sleep(1)
sys.exit(int(sys.argv[1]))
''')
checker = root/'checker.py'
checker.write_text('''import json,sys
from pathlib import Path
counter=Path(sys.argv[1]);mode=sys.argv[2]
n=int(counter.read_text())+1 if counter.exists() else 1
counter.write_text(str(n))
passed=mode=='ready' or mode=='recover' and n==2
retryable=mode in ('recover','exhaust')
Path(sys.argv[sys.argv.index('--result')+1]).write_text(json.dumps({'passed':passed,'retryable':retryable}))
sys.exit(0 if passed else 1)
''')
unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'],
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for mode, expected_calls, nav_exit, expected_result in [
('recover', 2, 0, 0), ('exhaust', 3, 0, 1),
('unknown', 1, 0, 1), ('ready', 1, 1, 1)]:
counter = root/(mode+'.count')
result = supervise([sys.executable, str(navigation), str(nav_exit)],
[sys.executable, str(checker), str(counter), mode], 3, 2)
CHECK(result == expected_result and int(counter.read_text()) == expected_calls,
f'{mode}: wrong retry count/result')
CHECK(unrelated.poll() is None, 'unrelated process was stopped')
finally:
stop_owned(unrelated)
print('PASS: 5 supervisor checks (recovery, limit, unknown/active refusal, no retry after ready, process ownership)')
if __name__ == '__main__':
main()
+129 -8
View File
@@ -8,16 +8,61 @@ import signal
import subprocess
import time
import uuid
from collections import Counter
import rclpy
from rclpy.node import Node
from rclpy.parameter import Parameter
from lifecycle_msgs.srv import GetState
from tf2_msgs.msg import TFMessage
from nav2_msgs.srv import IsPathValid
from rcl_interfaces.srv import GetParameters
from std_srvs.srv import Trigger
from rclpy.utilities import get_rmw_implementation_identifier
from nav2_startup import path_probe_request
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother',
'collision_monitor']
'collision_monitor', 'route_server', 'docking_server', 'following_server']
ENV_KEYS = ['RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'ROS_LOCALHOST_ONLY',
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER']
def process_environment(root_pid):
"""Only inspect this launch's descendants, and only middleware environment keys."""
parents = {}
for path in Path('/proc').glob('[0-9]*/status'):
try:
parent = next(line.split()[1] for line in path.read_text().splitlines()
if line.startswith('PPid:'))
parents[int(path.parent.name)] = int(parent)
except (OSError, StopIteration, ValueError):
continue
owned = {root_pid}
while True:
expanded = owned | {pid for pid, parent in parents.items() if parent in owned}
if expanded == owned:
break
owned = expanded
result = []
for pid in sorted(owned):
try:
base = Path('/proc')/str(pid)
env = dict(item.split('=', 1) for item in
(base/'environ').read_bytes().decode(errors='replace').split('\0') if '=' in item)
command = (base/'cmdline').read_bytes().decode(errors='replace').split('\0')
# Do not record full robot descriptions or unrelated environment variables.
result.append({'pid': pid, 'executable': command[:2],
'rmw_libraries': sorted({line.rsplit('/', 1)[-1] for line in
(base/'maps').read_text().splitlines()
if '/librmw_' in line and '.so' in line}),
'environment': {key: env.get(key) for key in ENV_KEYS}})
except OSError:
continue
return result
def main():
@@ -25,13 +70,17 @@ def main():
parser.add_argument('--map', type=Path, required=True)
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
parser.add_argument('--timeout', type=float, default=420.0,
help='whole-stack validation deadline, including up to three startup attempts')
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
args = parser.parse_args()
if not args.map.is_file():
parser.error('map missing')
args.output.mkdir(parents=True, exist_ok=True)
session = uuid.uuid4().hex[:12]
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
FASTDDS_BUILTIN_TRANSPORTS='UDPv4', ROS2CLI_DISABLE_DAEMON='1',
ROS2CLI_DISABLE_DAEMON='1',
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
workspace = Path(__file__).resolve().parents[1]
@@ -42,6 +91,7 @@ def main():
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
log = open(args.output/'stack.log', 'w', encoding='utf8')
started = time.monotonic()
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
rclpy.init()
@@ -62,9 +112,21 @@ def main():
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
path_client = node.create_client(IsPathValid, '/is_path_valid')
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
states = {}
processes = []
rviz = None
result = {}
try:
deadline = time.monotonic()+120
if args.rviz:
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
'-p', 'use_sim_time:=true'],
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
deadline = time.monotonic()+args.timeout
last_check = 0.0
stable_since = None
manager_completed = False
@@ -75,13 +137,22 @@ def main():
if time.monotonic()-last_check < 0.5:
continue
last_check = time.monotonic()
if not processes and time.monotonic()-started > 8:
processes = process_environment(process.pid)
states = {}
pending = {}
for name, client in clients.items():
if not client.service_is_ready():
continue
future = client.call_async(GetState.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=1)
pending[name] = client.call_async(GetState.Request())
poll_end = time.monotonic()+1
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
rclpy.spin_once(node, timeout_sec=0.02)
for name, future in pending.items():
if future.done() and future.result():
states[name] = future.result().current_state.id
else:
clients[name].remove_pending_request(future)
log_path = args.output/'stack.log'
text = log_path.read_text(errors='replace') if log_path.exists() else ''
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
@@ -93,16 +164,59 @@ def main():
break
else:
stable_since = None
processes = process_environment(process.pid)
names = sorted(set(node.get_node_names()))
result = {'launcher': args.launcher, 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
path_ready = path_client.wait_for_service(timeout_sec=2)
path_response = None
if path_ready:
future = path_client.call_async(path_probe_request())
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
if future.done() and future.result() is not None:
path_response = str(future.result())
manager_active = False
if active_client.wait_for_service(timeout_sec=1):
future = active_client.call_async(Trigger.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
manager_active = bool(future.done() and future.result() and future.result().success)
managed_nodes = []
if parameter_client.wait_for_service(timeout_sec=1):
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
if future.done() and future.result() and future.result().values:
managed_nodes = list(future.result().values[0].string_array_value)
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
'node_counts': dict(Counter(node.get_node_names())),
'services': dict(node.get_service_names_and_types()),
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
'manager_active': manager_active, 'managed_nodes': managed_nodes,
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
result['passed'] = (manager_completed and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
result['passed'] = (manager_completed and manager_active and path_response is not None
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
and counts['map_to_base_link'] == 0)
(args.output/'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2), flush=True)
if args.goal and result['passed']:
goal = subprocess.run([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200)
(args.output/'goal.log').write_text(goal.stdout)
result['goal_exit_code'] = goal.returncode
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout
result['passed'] = result['passed'] and goal.returncode == 0 and result['goal_succeeded']
(args.output/'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps({k: v for k, v in result.items() if k not in
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
if not result['passed']:
raise RuntimeError('stack integration validation failed')
except Exception as error:
result.update(passed=False, error=str(error))
(args.output/'result.json').write_text(json.dumps(result, indent=2))
raise
finally:
_ = subscription
if process.poll() is None:
@@ -112,6 +226,13 @@ def main():
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
if rviz is not None:
os.killpg(rviz.pid, signal.SIGINT)
try:
rviz.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(rviz.pid, signal.SIGKILL)
rviz.wait()
if log:
log.close()
node.destroy_node()