244 lines
13 KiB
Python
244 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Live integration check: isolated Gazebo + LIO + Nav2, no motion commands."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
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', '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():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
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}',
|
|
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]
|
|
log = None
|
|
if args.launcher == 'shell':
|
|
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
|
else:
|
|
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()
|
|
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
|
publishers = set()
|
|
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
|
|
|
def on_tf(msg, info):
|
|
for transform in msg.transforms:
|
|
if transform.header.frame_id != 'map':
|
|
continue
|
|
if transform.child_frame_id == 'odom':
|
|
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
|
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
|
counts['map_to_odom'] += 1
|
|
if transform.child_frame_id == 'base_link':
|
|
counts['map_to_base_link'] += 1
|
|
|
|
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:
|
|
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
|
|
while time.monotonic() < deadline:
|
|
rclpy.spin_once(node, timeout_sec=0.1)
|
|
if process.poll() is not None:
|
|
raise RuntimeError('stack exited')
|
|
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
|
|
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
|
|
for line in text.splitlines())
|
|
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed:
|
|
if stable_since is None:
|
|
stable_since = time.monotonic()
|
|
if time.monotonic()-stable_since >= 2:
|
|
break
|
|
else:
|
|
stable_since = None
|
|
processes = process_environment(process.pid)
|
|
names = sorted(set(node.get_node_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 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))
|
|
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:
|
|
os.killpg(process.pid, signal.SIGINT)
|
|
try:
|
|
process.wait(timeout=20)
|
|
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()
|
|
rclpy.shutdown()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|