repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/doxy-docs/build_doxy_sphinx.sh
rm -rf xml/* doxygen Doxyfile rm -rf build/* sphinx-build -b html -d build/doctrees source build/html
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/doxy-docs/Doxyfile
PROJECT_NAME = "Cyber RT Documents" XML_OUTPUT = xml INPUT = ../cyber.h ../init.h ../node ../record ../time ../timer ../component ../logger ../parameter ../service ../service_discovery ../python FILE_PATTERNS = *.h *.py RECURSIVE = YES GENERATE_LATEX = NO GENERATE_MAN = NO GENERATE_RTF = NO CASE_SENSE_NAMES = NO GENERATE_HTML = NO GENERATE_XML = YES RECURSIVE = YES QUIET = YES JAVADOC_AUTOBRIEF = YES WARN_IF_UNDOCUMENTED = NO MACRO_EXPANSION = YES PREDEFINED = IN_DOXYGEN
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/index.rst
Introduction ============= Apollo Cyber RT is an open source, high performance runtime framework designed specifically for autonomous driving scenarios. Based on a centralized computing model, it is greatly optimized for high concurrency, low latency, and high throughput in autonomous driving. During the last few years of the development of autonomous driving technologies, we have learned a lot from our previous experience with Apollo. The industry is evolving and so is Apollo. Going forward, Apollo has already moved from development to productization, with volume deployments in the real world, we see the demands for the highest level of robustness and performance. That’s why we spent years building and perfecting Apollo Cyber RT, which addresses that requirements of autonomous driving solutions. Key benefits of using Apollo Cyber RT: - Accelerate development + Well defined task interface with data fusion + Array of development tools + Large set of sensor drivers - Simplify deployment + Efficient and adaptive message communication + Configurable user level scheduler with resource awareness + Portable with fewer dependencies - Empower your own autonomous vehicles + The default open source runtime framework + Building blocks specifically designed for autonomous driving + Plug and play your own AD system .. toctree:: :caption: QUICKSTART :maxdepth: 1 CyberRT_Quick_Start.md CyberRT_Terms CyberRT_FAQs .. toctree:: :caption: TUTORIALS :maxdepth: 2 CyberRT_API_for_Developers CyberRT_Python_API.md CyberRT_Developer_Tools.md .. toctree:: :maxdepth: 2 :caption: ADVANCED TOPICS CyberRT_Docker.md CyberRT_Migration_Guide.md .. toctree:: :caption: API REFERENCE :maxdepth: 2 api/cppapi_index api/pythonapi_index
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Terms.md
Cyber RT Terms ================= This page describes the definitions of the most commonly used terminologies in Cyber RT. ## Component In an autonomous driving system, modules(like perception, localization, control systems...) exist in the form of components under Cyber RT. Each component communicates with the others through Cyber channels. The component concept not only decouples modules but also provides the flexibility for modules to be divided into components based individual module design. ## Channel Channels are used to manage data communication in Cyber RT. Users can publish/subscribe to the same channel to achieve p2p communication. ## Task Task is the abstract description of an asynchronous computation task in Cyber RT. ## Node Node is the fundamental building block of Cyber RT; every module contains and communicates through the node. A module can have different types of communication by defining read/write and/or service/client in a node. ## Reader/Writer Message read/write class from/to channel. Reader/Writer are normally created within a node as the major message transfer interface in Cyber RT. ## Service/Client Besides Reader/writer, Cyber RT also provides service/client pattern for module communication. It supports two-way communication between nodes. A client node will receive a response when a request is made to a service. ## Parameter Parameter service provides a global parameter access interface in Cyber RT. It's built based on the service/client pattern. ## Service discovery As a decentralized design framework, Cyber RT does not have a master/central node for service registration. All nodes are treated equally and can find other service nodes through `service discovery`. `UDP` is used in Service discovery. ## CRoutine Referred to as Coroutine concept, Cyber RT implemented CRoutine to optimize thread usage and system resource allocation. ## Scheduler To better support autonomous driving scenarios, Cyber RT provides different kinds of resource scheduling algorithms for developers to choose from. ## Message Message is the data unit used in Cyber RT for data transfer between modules. ## Dag file Dag file is the config file of module topology. You can define components used and upstream/downstream channels in the dag file. ## Launch files The Launch file provides an easy way to start modules. By defining one or multiple dag files in the launch file, you can start multiple modules at the same time. ## Record file The Record file is used to record messages sent/received to/from channels in Cyber RT. Reply record files can help reproduce the behavior of previous operations of Cyber RT.
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess import sphinx_rtd_theme on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: subprocess.call('cd ..; doxygen', shell=True) html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] def setup(app): app.add_stylesheet("main_stylesheet.css") extensions = ['breathe', 'recommonmark'] breathe_projects = {'Cyber RT Documents': '../xml'} templates_path = ['_templates'] html_static_path = ['_static'] source_suffix = { '.rst': 'restructuredtext', '.md': 'markdown', } master_doc = 'index' project = 'Cyber RT Documents' copyright = '2019, Apollo' author = 'Apollo Baidu' #html_logo = 'quantstack-white.svg' exclude_patterns = [] highlight_language = 'c++' pygments_style = 'sphinx' todo_include_todos = False htmlhelp_basename = 'CyberRTdoc'
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Developer_Tools.md
Apollo Cyber RT Developer Tools ================================== Apollo Cyber RT framework comes with a collection of useful tools for daily development, including one visualization tool cyber_visualizer and two command line tools cyber_monitor and cyber_recorder. *Note: apollo docker environment is required to use the tools, please follow apollo wiki to enter docker* All the tools from Apollo Cyber RT rely on Apollo Cyber RT library, so you must source the setup.bash file for environment setup before using any Apollo Cyber RT tools, shown as below: ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash ``` ## Cyber_visualizer ### Install and run `cyber_visualizer` is a visualization tool for displaying the channel data in Apollo Cyber RT. ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash username@computername:~$: cyber_visualizer ``` ### Interacting with cyber_visualizer - After launching cyber_visualizer, you will see the following interface: ![interface](images/cyber_visualizer1.png) - When data flow through channels in Apollo Cyber RT, the list of all channels are displayed under `ChannelNames` as seen in the figure below. For example, you can use the record tool(cyber_recorder) of Apollo Cyber RT to replay data from another terminal, then `cyber_visualizer` will receive information of all active channels(from replay data) and display it. ![channel information](images/cyber_visualizer2.png) - By clicking on options in toolbar, you can enable reference grid, display point clouds, add images, or display multiple camera's data at the same time. If you have `Show Grid` option enabled, you can set the color of the grid by double-clicking the `Color` item of the `Grid` list below `ChannelNames`. The default color is gray. You can also edit the value of `CellCount` to adjust the number of cells in the grid. As for a point cloud or an image, you can select the source channel through its `ChannelName` sub-item, and `Action` sub-item to play or stop the data from the corresponding channel. As shown in figure below, three cameras' channel data on the button sections and one point cloud channel data on the top section are displayed simultaneously. ![visualization](images/cyber_visualizer3.png) - To adjust the virtual camera in the 3D point cloud scene, you can right click on the point cloud display section. A dialog box will pop up as shown in figure below. ![visualization](images/cyber_visualizer4.png) The point cloud scene supports two types of cameras: Free and Target.(select Type from pop up dialog above) - **Free type Camera**: For this type of camera in the point cloud scene, you can change the pose of the camera by holding down either left or right mouse button and move it. To change the pitch of camera, you can scroll the mouse wheel. - **Target type Camera**: For this type of camera in the point cloud scene, to change the camera's viewing angle, you can hold down the left mouse button and then move it. To change the distance of the camera to the observed point (the default observation point is the coordinate system origin (0, 0,0)), you can scroll the mouse wheel. You can also modify the camera information directly in the dialog box to change the camera's observation status in the point cloud scene. And the "Step" item is the step value from the dialog box. Place the mouse on the image of the camera channel, you can double-click the left button to highlight the corresponding data channel on the left menu bar. Right click on the image to bring up menu for deleting the camera channel. Play and Pause buttons: when clicking the `Play` button, all channels will be shown. While when clicking the `Pause` button, all channels will stop showing on the tool. ## Cyber_monitor ### Install and run The command line tool `cyber_monitor` provides a clear view of the list of real time channel information Apollo Cyber RT in the terminal. ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash username@computername:~$: cyber_monitor ``` ### Useful commands #### Display help information Use the -h option to get help for cyber_monitor ```bash username@computername:~$: cyber_monitor -h ``` #### Specify the channel With the -c option, you can have cyber_monitor to monitor only a specified channel, such as: ```bash username@computername:~$: cyber_monitor -c ChannelName ``` ## Get familiar with UI of cyber_monitor After launching the command line tool, you will notice it is similar to cyber_visualizer. It automatically collects the information of all the channels through the topology and displays them in two columns (channel name, channel data type). The default display for channel information is in red. However, if there is data flowing through the a channel, the corresponding line of the channel is displayed in green. As shown in the image below: ![monitor](images/cyber_monitor.png) ### Interacting with cyber_monitor #### Common commands ``` ESC | q key ---- Exit Backspace ---- Back h | H ---- Show help page ``` #### Common command for topology and channel ``` PageDown | Ctrl+d --- Next PageUp | Ctrl+u --- Previous Up, down or w, s keys ---- Move the current highlight line up and down Right arrow or d key ---- Enter highlight line, display highlighted line data in detail Left arrow or a key ------ Return to the previous layer from the current Enter key ----- Same as d key ``` #### Commands only for topology ``` f | F ----- Display frame rate t | T ----- Display channel message type Space ----- Close|Open channel (only valid for channels with data arrival; yellow color after channel is closed) ``` #### Commands only for channel ``` i | I ----- Display channel Reader and Writer information b | B ------ Display channel message content ``` #### View the repeated data field in a channel ``` n | N ---- Repeat the next data in the domain m | M ---- Repeat one data on the domain ``` ## Cyber_recorder `cyber_recorder` is a record/playback tool provided by Apollo Cyber RT. It provides many useful functions, including recording a record file, playing back a record file, splitting a record file, checking the information of record file and etc. ### Install and run Launch cyber_recorder: ```bash $ source /your-path-to-apollo-install-dir/cyber/setup.bash $ cyber_recorder usage: cyber_recorder <command>> [<args>] The cyber_recorder commands are: info Show information of an exist record. play Play an exist record. record Record same topic. split Split an exist record. recover Recover an exist record. ``` ### Commands of cyber_recorder - To view the information of a record file: ``` $ cyber_recorder info -h usage: cyber_recorder info [options] -h, --help show help message ``` - To record a record file ``` $ cyber_recorder record -h usage: cyber_recorder record [options] -o, --output <file> output record file -a, --all all channels -c, --white-channel <name> only record the specified channel -k, --black-channel <name> not record the specified channel -i, --segment-interval <seconds> record segmented every n second(s) -m, --segment-size <MB> record segmented every n megabyte(s) -h, --help show help message ``` - To play back a record file: ``` $ cyber_recorder play -h usage: cyber_recorder play [options] -f, --file <file> input record file -a, --all play all -c, --white-channel <name> only play the specified channel -k, --black-channel <name> not play the specified channel -l, --loop loop play -r, --rate <1.0> multiply the play rate by FACTOR -b, --begin <2018-07-01 00:00:00> play the record begin at -e, --end <2018-07-01 00:01:00> play the record end at -s, --start <seconds> play started at n seconds -d, --delay <seconds> play delayed n seconds -p, --preload <seconds> play after trying to preload n second(s) -h, --help show help message ``` - To split a record file: ``` $ cyber_recorder split -h usage: cyber_recorder split [options] -f, --file <file> input record file -o, --output <file> output record file -a, --all all channels -c, --channel <name> channel name -b, --begin <2018-07-01 00:00:00> begin at assigned time -e, --end <2018-07-01 01:00:00> end at assigned time ``` - To repair a record file: ``` $ cyber_recorder recover -h usage: cyber_recorder recover [options] -f, --file <file> input record file -o, --output <file> output record file ``` ### Examples of using cyber_recorder #### Check the details of a record file ``` $ cyber_recorder info demo.record record_file: demo.record version: 1.0 duration: 19.995227 Seconds begin_time: 2018-04-17 06:25:36 end_time: 2018-04-17 06:25:55 size: 28275479 Bytes (26.965598 MB) is_complete: true message_number: 15379 channel_number: 16 channel_info: /apollo/localization/pose 2000 messages : apollo.localization.LocalizationEstimate /tf 4000 messages : apollo.transform.TransformStampeds /apollo/control 2000 messages : apollo.control.ControlCommand /apollo/sensor/gnss/odometry 2000 messages : apollo.localization.Gps /apollo/canbus/chassis 2000 messages : apollo.canbus.Chassis /apollo/sensor/gnss/imu 1999 messages : apollo.drivers.gnss.Imu /apollo/sensor/gnss/rtk_obs 41 messages : apollo.drivers.gnss.EpochObservation /apollo/sensor/gnss/ins_stat 20 messages : apollo.drivers.gnss.InsStat /apollo/sensor/gnss/best_pose 20 messages : apollo.drivers.gnss.GnssBestPose /apollo/perception/obstacles 400 messages : apollo.perception.PerceptionObstacles /apollo/prediction 400 messages : apollo.prediction.PredictionObstacles /apollo/sensor/conti_radar 270 messages : apollo.drivers.ContiRadar /apollo/planning 200 messages : apollo.planning.ADCTrajectory /apollo/monitor/static_info 1 messages : apollo.data.StaticInfo /apollo/sensor/gnss/rtk_eph 25 messages : apollo.drivers.gnss.GnssEphemeris /apollo/monitor 3 messages : apollo.common.monitor.MonitorMessage ``` #### Record a record file ``` $ cyber_recorder record -a [RUNNING] Record : total channel num : 1 total msg num : 5 ... ``` #### Replay a record file ``` $ cyber_recorder play -f 20180720202307.record file: 20180720202307.record, chunk_number: 1, begin_time: 1532089398663399667, end_time: 1532089404688079759, message_number: 75 please wait for loading and playing back record... Hit Ctrl+C to stop replay, or Space to pause. [RUNNING] Record Time: 1532089404.688080 Progress: 6.024680 / 6.024680 play finished. file: 20180720202307.record ``` ## rosbag_to\_record `rosbag_to_record` is a tool which can convert rosbag to recorder file provided by Apollo Cyber RT. Now the tool support following channel: ``` /apollo/perception/obstacles /apollo/planning /apollo/prediction /apollo/canbus/chassis /apollo/control /apollo/guardian /apollo/localization/pose /apollo/perception/traffic_light /apollo/drive_event /apollo/sensor/gnss/odometry /apollo/monitor/static_info /apollo/monitor /apollo/canbus/chassis_detail /apollo/control/pad /apollo/navigation /apollo/routing_request /apollo/routing_response /tf /tf_static /apollo/sensor/conti_radar /apollo/sensor/delphi_esr /apollo/sensor/gnss/best_pose /apollo/sensor/gnss/imu /apollo/sensor/gnss/ins_stat /apollo/sensor/gnss/rtk_eph /apollo/sensor/gnss/rtk_obs /apollo/sensor/velodyne64/compensator/PointCloud2 ``` ### Install and run Launch rosbag_to\_record: ```bash $ source /your-path-to-apollo-install-dir/cyber/setup.bash $ rosbag_to_record Usage: rosbag_to_record input.bag output.record ``` ### Example We can convert [Apollo2.5 demo bag](https://github.com/ApolloAuto/apollo/releases/download/v2.5.0/demo_2.5.bag) to record file. ```bash $ rosbag_to_record demo_2.5.bag demo.record record_file: demo.record version: 1.0 duration: 19.995227 Seconds begin_time: 2018-04-17 06:25:36 end_time: 2018-04-17 06:25:55 size: 28275479 Bytes (26.965598 MB) is_complete: true message_number: 15379 channel_number: 16 channel_info: /apollo/localization/pose 2000 messages : apollo.localization.LocalizationEstimate /tf 4000 messages : apollo.transform.TransformStampeds /apollo/control 2000 messages : apollo.control.ControlCommand /apollo/sensor/gnss/odometry 2000 messages : apollo.localization.Gps /apollo/canbus/chassis 2000 messages : apollo.canbus.Chassis /apollo/sensor/gnss/imu 1999 messages : apollo.drivers.gnss.Imu /apollo/sensor/gnss/rtk_obs 41 messages : apollo.drivers.gnss.EpochObservation /apollo/sensor/gnss/ins_stat 20 messages : apollo.drivers.gnss.InsStat /apollo/sensor/gnss/best_pose 20 messages : apollo.drivers.gnss.GnssBestPose /apollo/perception/obstacles 400 messages : apollo.perception.PerceptionObstacles /apollo/prediction 400 messages : apollo.prediction.PredictionObstacles /apollo/sensor/conti_radar 270 messages : apollo.drivers.ContiRadar /apollo/planning 200 messages : apollo.planning.ADCTrajectory /apollo/monitor/static_info 1 messages : apollo.data.StaticInfo /apollo/sensor/gnss/rtk_eph 25 messages : apollo.drivers.gnss.GnssEphemeris /apollo/monitor 3 messages : apollo.common.monitor.MonitorMessage Conversion finished! Took 0.505623051 seconds in total. ```
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Docker.md
# How to Develop Cyber RT inside Docker on Both x86_64 and ARM64 To make life easier, Apollo maintains Cyber Docker images and a number of scripts to help developers build and play with Cyber RT framework. Cyber Docker images are built upon Ubuntu 18.04, and comes with full support for Cyber RT framework. For those who are interested in Cyber RT only, this would be the ideal point to start with. **Note: Apollo team also maintains ARM64 Cyber Docker images which was tested on Jetson AGX Xavier. The same set of scripts are provided to run both on x86_64 and ARM64 platforms.** In the next section, we will show you how to play with Cyber Docker images. ## Build and Test Cyber RT inside Docker Run the following command to start Cyber Docker container: ```bash bash docker/scripts/cyber_start.sh ``` Or if you are in China, run: ```bash bash docker/scripts/cyber_start.sh -g cn ``` A Docker container named `apollo_cyber_$USER` will be started. **Note**: You will lose all your previous changes in the container if you have ran this command before. Unless you would like to start a fresh Docker environment. To log into the newly started Cyber container: ```bash bash docker/scripts/cyber_into.sh ``` **Note**: you can login and logout Cyber container multiple times as you wish, the Docker environment will stay there until the next time you start another Cyber container. To build Cyber RT only and run unit tests: ```bash ./apollo.sh build cyber ./apollo.sh test cyber ``` Or run with `--config=opt` for an optimized build/test. ```bash ./apollo.sh build --config=opt cyber ./apollo.sh test --config=opt cyber ``` You should be able to see that all the testcases passed.
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Python_API.md
Python API tutorial ===================== ## 1. Background The core functions of Cyber RT are developed in C++. We also provide more python interfaces to help developers build their own utilities for specific projects. ## 2. Cyber RT Python Interfaces The python interfaces of Cyber RT are wrapper the corresponding C++ interfaces. The implementation doesn't rely on other third-party tools, e.g. swig, which makes it easier to maintain. ## 3. Overview of Python Interfaces in Cyber RT So far, the python interfaces covers: * access the information of channels * server/client communication * query informatoin in record files * read and write from/to record files * Time/Duration/Rate related operations * Timer ### 3.1 Read/Write of Channels Steps shown as below: 1. First create a Node; 2. Create corresponding reader or writer; 3. If write to a channel, use write interface in writer. 4. If read from a channel, use the spin interface in the node, and process the messages in your callback function The interfaces are shown below: ```python class Node: """ Class for cyber Node wrapper. """ def create_writer(self, name, data_type, qos_depth=1): """ create a topic writer for send message to topic. @param self @param name str: topic name @param data_type proto: message class for serialization """ def create_reader(self, name, data_type, callback, args=None): """ create a topic reader for receive message from topic. @param self @param name str: topic name @param data_type proto: message class for serialization @callback fn: function to call (fn(data)) when data is received. If args is set, the function must accept the args as a second argument, i.e. fn(data, args) @args any: additional arguments to pass to the callback """ def create_client(self, name, request_data_type, response_data_type): """ """ def create_service(self, name, req_data_type, res_data_type, callback, args=None): def spin(self): """ spin in wait and process message. @param self """ class Writer(object): """ Class for cyber writer wrapper. """ def write(self, data): """ writer msg string """ ``` ### 3.2 Record Interfaces Read from record: 1. Create a RecordReader; 2. Read messages from Record; Write to record: 1. Create a RecordWriter 2. Write messages to record; The interfaces are shown below: ```python class RecordReader(object): """ Class for cyber RecordReader wrapper. """ def read_messages(self, start_time=0, end_time=18446744073709551615): """ read message from bag file. @param self @param start_time: @param end_time: @return: generator of (message, data_type, timestamp) """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ def get_headerstring(self): """ return message header string. """ def reset(self): """ return reset. "" return _CYBER_RECORD.PyRecordReader_Reset(self.record_reader) def get_channellist(self): """ return channel list. """ return _CYBER_RECORD.PyRecordReader_GetChannelList(self.record_reader) class RecordWriter(object): """ Class for cyber RecordWriter wrapper. """ def open(self, path): """ open record file for write. """ def write_channel(self, channel_name, type_name, proto_desc): """ writer channel by channelname,typename,protodesc """ def write_message(self, channel_name, data, time, raw = True): """ writer msg:channelname,data,time,is data raw """ def set_size_fileseg(self, size_kilobytes): """ return filesegment size. """ def set_intervaltime_fileseg(self, time_sec): """ return file interval time. """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ ``` ### 3.3 Time Interfaces ```python class Time(object): @staticmethod def now(): time_now = Time(_CYBER_TIME.PyTime_now()) return time_now @staticmethod def mono_time(): mono_time = Time(_CYBER_TIME.PyTime_mono_time()) return mono_time def to_sec(self): return _CYBER_TIME.PyTime_to_sec(self.time) def to_nsec(self): return _CYBER_TIME.PyTime_to_nsec(self.time) def sleep_until(self, nanoseconds): return _CYBER_TIME.PyTime_sleep_until(self.time, nanoseconds) ``` ### 3.4 Timer Interfaces ```python class Timer(object): def set_option(self, period, callback, oneshot=0): """ set the option of timer. @param period The period of the timer, unit is ms. @param callback The tasks that the timer needs to perform. @param oneshot 1:perform the callback only after the first timing cycle 0:perform the callback every timed period """ def start(self): def stop(self): ``` ## 4. Examples ### 4.1 Read from Channel (in cyber/python/examples/listener.py) ```python import sys sys.path.append("../") from cyber_py import cyber from modules.common.util.testdata.simple_pb2 import SimpleMessage def callback(data): """ reader message callback. """ print "="*80 print "py:reader callback msg->:" print data print "="*80 def test_listener_class(): """ reader message. """ print "=" * 120 test_node = cyber.Node("listener") test_node.create_reader("channel/chatter", SimpleMessage, callback) test_node.spin() if __name__ == '__main__': cyber.init() test_listener_class() cyber.shutdown() ``` ### 4.2 Write to Channel(in cyber/python/examples/talker.py) ```python from modules.common.util.testdata.simple_pb2 import SimpleMessage from cyber_py import cyber """Module for example of talker.""" import time import sys sys.path.append("../") def test_talker_class(): """ test talker. """ msg = SimpleMessage() msg.text = "talker:send Alex!" msg.integer = 0 test_node = cyber.Node("node_name1") g_count = 1 writer = test_node.create_writer("channel/chatter", SimpleMessage, 6) while not cyber.is_shutdown(): time.sleep(1) g_count = g_count + 1 msg.integer = g_count print "="*80 print "write msg -> %s" % msg writer.write(msg) if __name__ == '__main__': cyber.init() test_talker_class() cyber.shutdown() ``` ### 4.3 Read and Write Messages from/to Record File(in cyber/python/examples/record.py) ```python """Module for example of record.""" import time import sys sys.path.append("../") from cyber_py import cyber from cyber_py import record from google.protobuf.descriptor_pb2 import FileDescriptorProto from modules.common.util.testdata.simple_pb2 import SimpleMessage TEST_RECORD_FILE = "test02.record" CHAN_1 = "channel/chatter" CHAN_2 = "/test2" MSG_TYPE = "apollo.common.util.test.SimpleMessage" STR_10B = "1234567890" TEST_FILE = "test.record" def test_record_writer(writer_path): """ record writer. """ fwriter = record.RecordWriter() if not fwriter.open(writer_path): print "writer open failed!" return print "+++ begin to writer..." fwriter.write_channel(CHAN_1, MSG_TYPE, STR_10B) fwriter.write_message(CHAN_1, STR_10B, 1000) msg = SimpleMessage() msg.text = "AAAAAA" file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() fwriter.write_channel('chatter_a', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('chatter_a', msg, 998, False) fwriter.write_message("chatter_a", msg.SerializeToString(), 999) fwriter.close() def test_record_reader(reader_path): """ record reader. """ freader = record.RecordReader(reader_path) time.sleep(1) print "+"*80 print "+++begin to read..." count = 1 for channelname, msg, datatype, timestamp in freader.read_messages(): print "="*80 print "read [%d] msg" % count print "chnanel_name -> %s" % channelname print "msg -> %s" % msg print "msgtime -> %d" % timestamp print "msgnum -> %d" % freader.get_messagenumber(channelname) print "msgtype -> %s" % datatype count = count + 1 if __name__ == '__main__': cyber.init() test_record_writer(TEST_RECORD_FILE) test_record_reader(TEST_RECORD_FILE) cyber.shutdown() ```
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_FAQs.md
F.A.Q. ======= ## What is Apollo Cyber RT? Apollo's Cyber RT is an open source runtime framework designed specifically for autonomous driving scenarios. Based on a centralized computing model, it is highly optimized for performance, latency, and data throughput --- ## Why did we decide to work on a new runtime framework? - During years of development of autonomous driving technologies, we have learned a lot from our previous experience with Apollo. In autonomous driving scenarious, we need an effective centralized computing model, with demands for high performance, including high concurrency, low latency and high throughput。 - The industry is evolving, so does Apollo. Going forward, Apollo has already moved from development to productization, with volume deployments in the real world, we see the demands for the highest robustness and high performance. That’s why we spent years of building Apollo Cyber RT, which addresses that requirements of autonomous driving solutions. --- ## What are the advantages of the new runtime framework? - Accelerate development + Well defined task interface with data fusion + Array of development tools + Large set of sensor drivers - Simplify deployment + Efficient and adaptive message communication + Configurable user level scheduler with resource awareness + Portable with fewer dependencies - Empower your own autonomous vehicles + The default open source runtime framework + Building blocks specifically designed for autonomous driving + Plug and play your own AD system --- ## Can we still use the data that we have collected? - If the data you have collected is compatible with the previous versions of Apollo, you could use our recommended conversion tools to make the data compliant with our new runtime framework - If you created a customized data format, then the previously generated data will not be supported by the new runtime framework --- ## Will you continue to support ROS? We will continue to support previous Apollo releases (3.0 and before) based on ROS. We do appreciate you continue growing with us and highly encourage you to move to Apollo 3.5. While we know that some of our developers would prefer to work on ROS, we do hope you will understand why Apollo as a team cannot continue to support ROS in our future releases as we strive to work towards developing a more holistic platform that meets automotive standards. --- ## Will Apollo Cyber RT affect regular code development? If you have not modified anything at runtime framework layer and have only worked on Apollo's module code base, you will not be affected by the introduction of our new runtime framework as most of time you would only need to re-interface the access of the input and output data. Additional documents are under [cyber](https://github.com/ApolloAuto/apollo/tree/master/docs/cyber/) with more details. --- ## Recommended setup for Apollo Cyber RT - Currently the runtime framework only supports running on Trusty (Ubuntu 14.04) - The runtime framework also uses apollo's docker environment - It is recommended to run source setup.bash when opening a new terminal - Fork and clone the Apollo repo with the new framework code which can be found at [apollo/cyber](https://github.com/ApolloAuto/apollo/tree/master/cyber/) ## How to enable SHM to decrease the latency? To decrease number of threads, the readable notification mechanism of shared memory was changed in CyberRT. The default mechanism is UDP multicast, and system call(sendto) will cause some latency. So, to decrease the latency, you can change the mechanism, The steps are listed as following: 1. update the CyberRT to the latest version; 2. uncomment the transport_conf in https://github.com/ApolloAuto/apollo/blob/master/cyber/conf/cyber.pb.conf; 3. change **notifier_type** of **shm_conf** from "multicast" to "condition"; 4. build CyberRT with opt like `bazel build -c opt --copt=-fpic //cyber/...`; 5. run talker and listener; Note:You can select the corresponding transmission method according to the relationship between nodes.For example, the default configuration is **INTRA** in the process, **SHM** between the host process, and **RTPS** across the host. Of course you can change all three to RTPS. Or change `same_proc` and `diff_proc` to **SHM**; ## How to use the no serialization message? The message types supported by Cyber RT include both serializable structured data like protobuf and raw sequence of bytes. You can refer the sample code: - apollo::cyber::message::RawMessage - talker: https://github.com/gruminions/apollo/blob/record/cyber/examples/talker.cc - listener: https://github.com/gruminions/apollo/blob/record/cyber/examples/listener.cc ## How to configure multiple hosts communication? Make sure the two hosts(or more) are under the same network segment of the local area network, Like `192.168.10.6` and `192.168.10.7`. You just need to modify `CYBER_IP` of `/apollo/cyber/setup.bash` ```bash export CYBER_IP=127.0.0.1 ``` Suppose you have two hosts A and B,the ip of A is `192.168.10.6`, and the ip of B is `192.168.10.7`. Then set `CYBER_IP` to `192.168.10.6` on host A, and set `CYBER_IP` to `192.168.10.7` on host B. Now host A can communicate with host B. --- More FAQs to follow...
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_API_for_Developers.md
Cyber RT API tutorial ============================= This document provides an extensive technical deep dive into how to create, manipulate and use Cyber RT's API. ## Table of Contents - [Talker-Listener](#Talker-Listener) - [Service Creation and Use](#Service-Creation-and-Use) - [Param parameter service](#Param-parameter-service) - [Log API](#LOG-API) - [Building a module based on Component](#Building-a-module-based-on-Component) - [Launch](#Launch) - [Timer](#timer) - [Time API](#use-of-time) - [Record file: Read and Write](#Record-file-Read-and-Write) - [C++ API Directory](##API-Directory) - [Node](#node-api) - [Writer](#writer-api) - [Client](#client-api) - [Parameter](#parameter-api) - [Timer](#timer-api) - [Time](#timer-api) - [Duration](#duration-api) - [Rate](#rate-api) - [RecordReader](#recordreader-api) - [RecordWriter](#recordwriter-api) ## Talker-Listener The first part of demonstrating CyberRT API is to understand the Talker/Listener example. Following are three essential concepts: node (basic unit), reader(facility to read message) and writer(facility to write message) of the example. ### Create a node In the CyberRT framework, the node is the most fundamental unit, similar to the role of a `handle`. When creating a specific functional object (writer, reader, etc.), you need to create it based on an existing node instance. The node creation interface is as follows: ```cpp std::unique_ptr<Node> apollo::cyber::CreateNode(const std::string& node_name, const std::string& name_space = ""); ``` - Parameters: - node_name: name of the node, globally unique identifier - name_space: name of the space where the node is located > name_space is empty by default. It is the name of the space concatenated with node_name. The format is `/namespace/node_name` - Return value - An exclusive smart pointer to Node - Error Conditions - when `cyber::Init()` has not called, the system is in an uninitialized state, unable to create a node, return nullptr ### Create a writer The writer is the basic facility used in CyberRT to send messages. Every writer corresponds to a channel with a specific data type. The writer is created by the `CreateWriter` interface in the node class. The interfaces are listed as below: ```cpp template <typename MessageT> auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>>; template <typename MessageT> auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>>; ``` - Parameters: - channel_name: the name of the channel to write to - MessageT: The type of message to be written out - Return value - Shared pointer to the Writer object ### Create a reader The reader is the basic facility used in cyber to receive messages. Reader has to be bound to a callback function when it is created. When a new message arrives in the channel, the callback will be called. The reader is created by the `CreateReader` interface of the node class. The interfaces are listed as below: ```cpp template <typename MessageT> auto CreateReader(const std::string& channel_name, const std::function<void(const std::shared_ptr<MessageT>&)>& reader_func) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; template <typename MessageT> auto CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; ``` - Parameters: - MessageT: The type of message to read - channel_name: the name of the channel to receive from - reader_func: callback function to process the messages - Return value - Shared pointer to the Reader object ### Code Example #### Talker (cyber/examples/talker.cc) ```cpp #include "cyber/cyber.h" #include "cyber/proto/chatter.pb.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::cyber::proto::Chatter; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node std::shared_ptr<apollo::cyber::Node> talker_node( apollo::cyber::CreateNode("talker")); // create talker auto talker = talker_node->CreateWriter<Chatter>("channel/chatter"); Rate rate(1.0); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<apollo::cyber::proto::Chatter>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_lidar_timestamp(Time::Now().ToNanosecond()); msg->set_seq(seq++); msg->set_content("Hello, apollo!"); talker->Write(msg); AINFO << "talker sent a message!"; rate.Sleep(); } return 0; } ``` #### Listener (cyber/examples/listener.cc) ```cpp #include "cyber/cyber.h" #include "cyber/proto/chatter.pb.h" void MessageCallback( const std::shared_ptr<apollo::cyber::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cyber::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; } ``` #### Bazel BUILD file(cyber/samples/BUILD) ```python cc_binary( name = "talker", srcs = [ "talker.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "listener", srcs = [ "listener.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` #### Build and Run - Build: bazel build cyber/examples/… - Run talker/listener in different terminals: - ./bazel-bin/cyber/examples/talker - ./bazel-bin/cyber/examples/listener - Examine the results: you should see message printing out on listener. ## Service Creation and Use ### Introduction In an autonomous driving system, there are many scenarios that require more from module communication than just sending or receiving messages. Service is another way of communication between nodes. Unlike channel, service implements `two-way` communication, e.g. a node obtains a response by sending a request. This section introduces the `service` module in CyberRT API with examples. ### Demo - Example Problem: create a client-server model that pass Driver.proto back and forth. When a request is sent in by the client, the server parses/processes the request and returns the response. The implementation of the demo mainly includes the following steps. #### Define request and response messages All messages in cyber are in the `protobuf` format. Any protobuf message with serialize/deserialize interfaces can be used as the service request and response message. `Driver` in examples.proto is used as service request and response in this example: ```protobuf // filename: examples.proto syntax = "proto2"; package apollo.cyber.examples.proto; message Driver { optional string content = 1; optional uint64 msg_id = 2; optional uint64 timestamp = 3; }; ``` #### Create a service and a client ```cpp // filename: cyber/examples/service.cc #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; int main(int argc, char* argv[]) { apollo::cyber::Init(argv[0]); std::shared_ptr<apollo::cyber::Node> node( apollo::cyber::CreateNode("start_node")); auto server = node->CreateService<Driver, Driver>( "test_server", [](const std::shared_ptr<Driver>& request, std::shared_ptr<Driver>& response) { AINFO << "server: I am driver server"; static uint64_t id = 0; ++id; response->set_msg_id(id); response->set_timestamp(0); }); auto client = node->CreateClient<Driver, Driver>("test_server"); auto driver_msg = std::make_shared<Driver>(); driver_msg->set_msg_id(0); driver_msg->set_timestamp(0); while (apollo::cyber::OK()) { auto res = client->SendRequest(driver_msg); if (res != nullptr) { AINFO << "client: response: " << res->ShortDebugString(); } else { AINFO << "client: service may not ready."; } sleep(1); } apollo::cyber::WaitForShutdown(); return 0; } ``` #### Bazel build file ```python cc_binary( name = "service", srcs = [ "service.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` #### Build and run - Build service/client: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/service - Examining result: you should see content below in apollo/data/log/service.INFO ``` txt I1124 16:36:44.568845 14965 service.cc:30] [service] server: i am driver server I1124 16:36:44.569031 14949 service.cc:43] [service] client: response: msg_id: 1 timestamp: 0 I1124 16:36:45.569514 14966 service.cc:30] [service] server: i am driver server I1124 16:36:45.569932 14949 service.cc:43] [service] client: response: msg_id: 2 timestamp: 0 I1124 16:36:46.570627 14967 service.cc:30] [service] server: i am driver server I1124 16:36:46.571024 14949 service.cc:43] [service] client: response: msg_id: 3 timestamp: 0 I1124 16:36:47.571566 14968 service.cc:30] [service] server: i am driver server I1124 16:36:47.571962 14949 service.cc:43] [service] client: response: msg_id: 4 timestamp: 0 I1124 16:36:48.572634 14969 service.cc:30] [service] server: i am driver server I1124 16:36:48.573030 14949 service.cc:43] [service] client: response: msg_id: 5 timestamp: 0 ``` ### Precautions - When registering a service, note that duplicate service names are not allowed - The node name applied when registering the server and client should not be duplicated either ## Parameter Service The Parameter Service is used for shared data between nodes, and provides basic operations such as `set`, `get`, and `list`. The Parameter Service is based on the `Service` implementation and contains service and client. ### Parameter Object #### Supported Data types All parameters passed through cyber are `apollo::cyber::Parameter` objects, the table below lists the 5 supported parameter types. Parameter type | C++ data type | protobuf data type :------------- | :------------- | :-------------- apollo::cyber::proto::ParamType::INT | int64_t | int64 apollo::cyber::proto::ParamType::DOUBLE | double | double apollo::cyber::proto::ParamType::BOOL | bool |bool apollo::cyber::proto::ParamType::STRING | std::string | string apollo::cyber::proto::ParamType::PROTOBUF | std::string | string apollo::cyber::proto::ParamType::NOT_SET | - | - Besides the 5 types above, Parameter also supports interface with protobuf object as incoming parameter. Post performing serialization processes the object and converts it to the STRING type for transfer. #### Creating the Parameter Object Supported constructors: ```cpp Parameter(); // Name is empty, type is NOT_SET explicit Parameter(const Parameter& parameter); explicit Parameter(const std::string& name); // type为NOT_SET Parameter(const std::string& name, const bool bool_value); Parameter(const std::string& name, const int int_value); Parameter(const std::string& name, const int64_t int_value); Parameter(const std::string& name, const float double_value); Parameter(const std::string& name, const double double_value); Parameter(const std::string& name, const std::string& string_value); Parameter(const std::string& name, const char* string_value); Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc); Parameter(const std::string& name, const google::protobuf::Message& msg); ``` Sample code of using Parameter object: ```cpp Parameter a("int", 10); Parameter b("bool", true); Parameter c("double", 0.1); Parameter d("string", "cyber"); Parameter e("string", std::string("cyber")); // proto message Chatter Chatter chatter; Parameter f("chatter", chatter); std::string msg_str(""); chatter.SerializeToString(&msg_str); std::string msg_desc(""); ProtobufFactory::GetDescriptorString(chatter, &msg_desc); Parameter g("chatter", msg_str, Chatter::descriptor()->full_name(), msg_desc); ``` #### Interface and Data Reading Interface list: ```cpp inline ParamType type() const; inline std::string TypeName() const; inline std::string Descriptor() const; inline const std::string Name() const; inline bool AsBool() const; inline int64_t AsInt64() const; inline double AsDouble() const; inline const std::string AsString() const; std::string DebugString() const; template <typename Type> typename std::enable_if<std::is_base_of<google::protobuf::Message, Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_integral<Type>::value && !std::is_same<Type, bool>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_floating_point<Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_convertible<Type, std::string>::value, const std::string&>::type value() const; template <typename Type> typename std::enable_if<std::is_same<Type, bool>::value, bool>::type value() const; ``` An example of how to use those interfaces: ```cpp Parameter a("int", 10); a.Name(); // return int a.Type(); // return apollo::cyber::proto::ParamType::INT a.TypeName(); // return string: INT a.DebugString(); // return string: {name: "int", type: "INT", value: 10} int x = a.AsInt64(); // x = 10 x = a.value<int64_t>(); // x = 10 x = a.AsString(); // Undefined behavior, error log prompt f.TypeName(); // return string: chatter auto chatter = f.value<Chatter>(); ``` ### Parameter Service If a node wants to provide a Parameter Service to other nodes, then you need to create a `ParameterService`. ```cpp /** * @brief Construct a new ParameterService object * * @param node shared_ptr of the node handler */ explicit ParameterService(const std::shared_ptr<Node>& node); ``` Since all parameters are stored in the parameter service object, the parameters can be manipulated directly in the ParameterService without sending a service request. **Setting parameters:** ```cpp /** * @brief Set the Parameter object * * @param parameter parameter to be set */ void SetParameter(const Parameter& parameter); ``` **Getting parameters:** ```cpp /** * @brief Get the Parameter object * * @param param_name * @param parameter the pointer to store * @return true * @return false call service fail or timeout */ bool GetParameter(const std::string& param_name, Parameter* parameter); ``` **Getting the list of parameters:** ```cpp /** * @brief Get all the Parameter objects * * @param parameters pointer of vector to store all the parameters * @return true * @return false call service fail or timeout */ bool ListParameters(std::vector<Parameter>* parameters); ``` ### Parameter Client If a node wants to use parameter services of other nodes, you need to create a `ParameterClient`. ```cpp /** * @brief Construct a new ParameterClient object * * @param node shared_ptr of the node handler * @param service_node_name node name which provide a param services */ ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name); ``` You could also perform `SetParameter`, `GetParameter` and `ListParameters` mentioned under [Parameter Service](#Parameter-Service). ### Demo - example ```cpp #include "cyber/cyber.h" #include "cyber/parameter/parameter_client.h" #include "cyber/parameter/parameter_server.h" using apollo::cyber::Parameter; using apollo::cyber::ParameterServer; using apollo::cyber::ParameterClient; int main(int argc, char** argv) { apollo::cyber::Init(*argv); std::shared_ptr<apollo::cyber::Node> node = apollo::cyber::CreateNode("parameter"); auto param_server = std::make_shared<ParameterServer>(node); auto param_client = std::make_shared<ParameterClient>(node, "parameter"); param_server->SetParameter(Parameter("int", 1)); Parameter parameter; param_server->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); param_client->SetParameter(Parameter("string", "test")); param_client->GetParameter("string", &parameter); AINFO << "string: " << parameter.AsString(); param_client->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); return 0; } ``` #### Build and run - Build: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/paramserver ## Log API ### Log library Cyber log library is built on top of glog. The following header files need to be included: ```cpp #include "cyber/common/log.h" #include "cyber/init.h" ``` ### Log configuration Default global config path: cyber/setup.bash The configs below could be modified by devloper: ``` export GLOG_log_dir=/apollo/data/log export GLOG_alsologtostderr=0 export GLOG_colorlogtostderr=1 export GLOG_minloglevel=0 ``` ### Log initialization Call the Init method at the code entry to initialize the log: ```cpp++ apollo::cyber::cyber::Init(argv[0]) is initialized. If no macro definition is made in the previous component, the corresponding log is printed to the binary log. ``` ### Log output macro Log library is encapsulated in Log printing macros. The related log macros are used as follows: ```cpp ADEBUG << "hello cyber."; AINFO << "hello cyber."; AWARN << "hello cyber."; AERROR << "hello cyber."; AFATAL << "hello cyber."; ``` ### Log format The format is `<MODULE_NAME>.log.<LOG_LEVEL>.<datetime>.<process_id>` ### About log files Currently, the only different output behavior from default glog is that different log levels of a module will be written into the same log file. ## Building a module based on Component ### Key concepts #### 1. Component The component is the base class that Cyber RT provides to build application modules. Each specific application module can inherit the Component class and define its own `Init` and `Proc` functions so that it can be loaded into the Cyber framework. #### 2. Binary vs Component There are two options to use Cyber RT framework for applications: - Binary based: the application is compiled separately into a binary, which communicates with other cyber modules by creating its own `Reader` and `Writer`. - Component based: the application is compiled into a Shared Library. By inheriting the Component class and writing the corresponding dag description file, the Cyber RT framework will load and run the application dynamically. ##### The essential Component interface - The component's `Init()` function is like the main function that does some initialization of the algorithm. - Component's `Proc()` function works like Reader's callback function that is called by the framework when a message arrives. ##### Advantages of using Component - Component can be loaded into different processes through the launch file, and the deployment is flexible. - Component can change the received channel name by modifying the dag file without recompiling. - Component supports receiving multiple types of data. - Component supports providing multiple fusion strategies. #### 3. Dag file format An example dag file: ```protobuf # Define all coms in DAG streaming. module_config { module_library : "lib/libperception_component.so" components { class_name : "PerceptionComponent" config { name : "perception" readers { channel: "perception/channel_name" } } } timer_components { class_name : "DriverComponent" config { name : "driver" interval : 100 } } } ``` - **module_library**: If you want to load the .so library the root directory is the working directory of cyber (the same directory of `setup.bash`) - **components & timer_component**: Select the base component class type that needs to be loaded. - **class_name**: the name of the component class to load - **name**: the loaded class_name as the identifier of the loading example - **readers**: Data received by the current component, supporting 1-3 channels of data. ### Demo - examples #### Common_component_example(cyber/examples/common_component_example/*) Header definition(common_component_example.h) ```cpp #include <memory> #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; using apollo::cyber::Component; using apollo::cyber::ComponentBase; class Commontestcomponent : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(Commontestcomponent) ``` Cpp file implementation(common_component_example.cc) ```cpp #include "cyber/examples/common_component_smaple/common_component_example.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" bool Commontestcomponent::Init() { AINFO << "Commontest component init"; return true; } bool Commontestcomponent::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start commontest component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; } ``` #### Timer_component_example(cyber/examples/timer_component_example/*) Header definition(timer_component_example.h) ```cpp #include <memory> #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/component/timer_component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::TimerComponent; using apollo::cyber::Writer; class TimertestComponent : public TimerComponent { public: bool Init() override; bool Proc() override; private: std::shared_ptr<Writer<Driver>> driver_writer_ = nullptr; }; CYBER_REGISTER_COMPONENT(TimertestComponent) ``` Cpp file implementation(timer_component_example.cc) ```cpp #include "cyber/examples/timer_component_example/timer_component_example.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" bool TimertestComponent::Init() { driver_writer_ = node_->CreateWriter<Driver>("/carstatus/channel"); return true; } bool TimertestComponent::Proc() { static int i = 0; auto out_msg = std::make_shared<Driver>(); out_msg->set_msg_id(i++); driver_writer_->Write(out_msg); AINFO << "timertestcomponent: Write drivermsg->" << out_msg->ShortDebugString(); return true; } ``` #### Build and run Use timertestcomponent as example: - Build: bazel build cyber/examples/timer_component_smaple/… - Run: mainboard -d cyber/examples/timer_component_smaple/timer.dag ### Precautions - Component needs to be registered to load the class through SharedLibrary. The registration interface looks like: ```cpp CYBER_REGISTER_COMPONENT(DriverComponent) ``` If you use a namespace when registering, you also need to add a namespace when you define it in the dag file. - The configuration files of the Component and TimerComponent are different, please be careful not to mix the two up. ## Launch **cyber_launch** is the launcher of the Cyber RT framework. It starts multiple mainboards according to the launch file, and loads different components into different mainboards according to the dag file. cyber_launch supports two scenarios for dynamically loading components or starting Binary programs in a child process. ### Launch File Format ```xml <cyber> <module> <name>driver</name> <dag_conf>driver.dag</dag_conf> <process_name></process_name> <exception_handler>exit</exception_handler> </module> <module> <name>perception</name> <dag_conf>perception.dag</dag_conf> <process_name></process_name> <exception_handler>respawn</exception_handler> </module> <module> <name>planning</name> <dag_conf>planning.dag</dag_conf> <process_name></process_name> </module> </cyber> ``` **Module**: Each loaded component or binary is a module - **name** is the loaded module name - **dag_conf** is the name of the corresponding dag file of the component - **process_name** is the name of the mainboard process once started, and the same component of process_name will be loaded and run in the same process. - **exception_handler** is the handler method when the exception occurs in the process. The value can be exit or respawn listed below. - exit, which means that the entire process needs to stop running when the current process exits abnormally. - respawn, the current process needs to be restarted after abnormal exit. Start this process. If there is no such thing as it is empty, it means no treatment. Can be controlled by the user according to the specific conditions of the process ## Timer Timer can be used to create a timed task to run on a periodic basis, or to run only once ### Timer Interface ```cpp /** * @brief Construct a new Timer object * * @param period The period of the timer, unit is ms * @param callback The tasks that the timer needs to perform * @param oneshot True: perform the callback only after the first timing cycle * False: perform the callback every timed period */ Timer(uint32_t period, std::function<void()> callback, bool oneshot); ``` Or you could encapsulate the parameters into a timer option as follows: ```cpp struct TimerOption { uint32_t period; // The period of the timer, unit is ms std::function<void()> callback; // The tasks that the timer needs to perform bool oneshot; // True: perform the callback only after the first timing cycle // False: perform the callback every timed period }; /** * @brief Construct a new Timer object * * @param opt Timer option */ explicit Timer(TimerOption opt); ``` ### Start Timer After creating a Timer instance, you must call `Timer::Start()` to start the timer. ### Stop Timer When you need to manually stop a timer that has already started, you can call the `Timer::Stop()` interface. ### Demo - example ```cpp #include <iostream> #include "cyber/cyber.h" int main(int argc, char** argv) { cyber::Init(argv[0]); // Print current time every 100ms cyber::Timer timer(100, [](){ std::cout << cyber::Time::Now() << std::endl; }, false); timer.Start() sleep(1); timer.Stop(); } ``` ## Time API Time is a class used to manage time; it can be used for current time acquisition, time-consuming calculation, time conversion, and so on. The time interfaces are as follows: ```cpp // constructor, passing in a different value to construct Time Time(uint64_t nanoseconds); //uint64_t, in nanoseconds Time(int nanoseconds); // int type, unit: nanoseconds Time(double seconds); // double, in seconds Time(uint32_t seconds, uint32_t nanoseconds); // seconds seconds + nanoseconds nanoseconds Static Time Now(); // Get the current time Double ToSecond() const; // convert to seconds Uint64_t ToNanosecond() const; // Convert to nanoseconds Std::string ToString() const; // Convert to a string in the format "2018-07-10 20:21:51.123456789" Bool IsZero() const; // Determine if the time is 0 ``` A code example can be seen below: ```cpp #include <iostream> #include "cyber/cyber.h" #include "cyber/duration.h" int main(int argc, char** argv) { cyber::Init(argv[0]); Time t1(1531225311123456789UL); std::cout << t1.ToString() << std::endl; // 2018-07-10 20:21:51.123456789 // Duration time interval Time t1(100); Duration d(200); Time t2(300); assert(d == (t1-t2)); // true } ``` ## Record file: Read and Write ### Reading the Reader file **RecordReader** is the component used to read messages in the cyber framework. Each RecordReader can open an existing record file through the `Open` method, and the thread will asynchronously read the information in the record file. The user only needs to execute ReadMessage to extract the latest message in RecordReader, and then get the message information through GetCurrentMessageChannelName, GetCurrentRawMessage, GetCurrentMessageTime. **RecordWriter** is the component used to record messages in the cyber framework. Each RecordWriter can create a new record file through the Open method. The user only needs to execute WriteMessage and WriteChannel to write message and channel information, and the writing process is asynchronous. ### Demo - example(cyber/examples/record.cc) Write 100 RawMessage to`TEST_FILE` through `test_write` method, then read them out through `test_read` method. ```cpp #include <string> #include "cyber/cyber.h" #include "cyber/message/raw_message.h" #include "cyber/proto/record.pb.h" #include "cyber/record/record_message.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" using ::apollo::cyber::record::RecordReader; using ::apollo::cyber::record::RecordWriter; using ::apollo::cyber::record::RecordMessage; using apollo::cyber::message::RawMessage; const char CHANNEL_NAME_1[] = "/test/channel1"; const char CHANNEL_NAME_2[] = "/test/channel2"; const char MESSAGE_TYPE_1[] = "apollo.cyber.proto.Test"; const char MESSAGE_TYPE_2[] = "apollo.cyber.proto.Channel"; const char PROTO_DESC[] = "1234567890"; const char STR_10B[] = "1234567890"; const char TEST_FILE[] = "test.record"; void test_write(const std::string &writefile) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(writefile); writer.WriteChannel(CHANNEL_NAME_1, MESSAGE_TYPE_1, PROTO_DESC); for (uint32_t i = 0; i < 100; ++i) { auto msg = std::make_shared<RawMessage>("abc" + std::to_string(i)); writer.WriteMessage(CHANNEL_NAME_1, msg, 888 + i); } writer.Close(); } void test_read(const std::string &readfile) { RecordReader reader(readfile); RecordMessage message; uint64_t msg_count = reader.GetMessageNumber(CHANNEL_NAME_1); AINFO << "MSGTYPE: " << reader.GetMessageType(CHANNEL_NAME_1); AINFO << "MSGDESC: " << reader.GetProtoDesc(CHANNEL_NAME_1); // read all message uint64_t i = 0; uint64_t valid = 0; for (i = 0; i < msg_count; ++i) { if (reader.ReadMessage(&message)) { AINFO << "msg[" << i << "]-> " << "channel name: " << message.channel_name << "; content: " << message.content << "; msg time: " << message.time; valid++; } else { AERROR << "read msg[" << i << "] failed"; } } AINFO << "static msg================="; AINFO << "MSG validmsg:totalcount: " << valid << ":" << msg_count; } int main(int argc, char *argv[]) { apollo::cyber::Init(argv[0]); test_write(TEST_FILE); sleep(1); test_read(TEST_FILE); return 0; } ``` #### Build and run - Build: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/record - Examining result: ``` I1124 16:56:27.248200 15118 record.cc:64] [record] msg[0]-> channel name: /test/channel1; content: abc0; msg time: 888 I1124 16:56:27.248227 15118 record.cc:64] [record] msg[1]-> channel name: /test/channel1; content: abc1; msg time: 889 I1124 16:56:27.248239 15118 record.cc:64] [record] msg[2]-> channel name: /test/channel1; content: abc2; msg time: 890 I1124 16:56:27.248252 15118 record.cc:64] [record] msg[3]-> channel name: /test/channel1; content: abc3; msg time: 891 I1124 16:56:27.248297 15118 record.cc:64] [record] msg[4]-> channel name: /test/channel1; content: abc4; msg time: 892 I1124 16:56:27.248378 15118 record.cc:64] [record] msg[5]-> channel name: /test/channel1; content: abc5; msg time: 893 ... I1124 16:56:27.250422 15118 record.cc:73] [record] static msg================= I1124 16:56:27.250434 15118 record.cc:74] [record] MSG validmsg:totalcount: 100:100 ``` ## API Directory ### Node API For additional information and examples, refer to [Node](#node) ### API List ```cpp //create writer with user-define attr and message type auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<transport::Writer<MessageT>>; //create reader with user-define attr, callback and message type auto CreateReader(const proto::RoleAttributes& role_attr, const croutine::CRoutineFunc<MessageT>& reader_func) -> std::shared_ptr<transport::Reader<MessageT>>; //create writer with specific channel name and message type auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<transport::Writer<MessageT>>; //create reader with specific channel name, callback and message type auto CreateReader(const std::string& channel_name, const croutine::CRoutineFunc<MessageT>& reader_func) -> std::shared_ptr<transport::Reader<MessageT>>; //create reader with user-define config, callback and message type auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<cybertron::Reader<MessageT>>; //create service with name and specific callback auto CreateService(const std::string& service_name, const typename service::Service<Request, Response>::ServiceCallback& service_calllback) -> std::shared_ptr<service::Service<Request, Response>>; //create client with name to send request to server auto CreateClient(const std::string& service_name) -> std::shared_ptr<service::Client<Request, Response>>; ``` ## Writer API For additional information and examples, refer to [Writer](#writer) ### API List ```cpp bool Write(const std::shared_ptr<MessageT>& message); ``` ## Client API For additional information and examples, refer to [Client](#service-creation-and-use) ### API List ```cpp SharedResponse SendRequest(SharedRequest request, const std::chrono::seconds& timeout_s = std::chrono::seconds(5)); SharedResponse SendRequest(const Request& request, const std::chrono::seconds& timeout_s = std::chrono::seconds(5)); ``` ## Parameter API The interface that the user uses to perform parameter related operations: - Set the parameter related API. - Read the parameter related API. - Create a ParameterService to provide parameter service related APIs for other nodes. - Create a ParameterClient that uses the parameters provided by other nodes to service related APIs. For additional information and examples, refer to [Parameter](##param-parameter-service) ### API List - Setting parameters ```cpp Parameter(); // Name is empty, type is NOT_SET explicit Parameter(const Parameter& parameter); explicit Parameter(const std::string& name); // Type is NOT_SET Parameter(const std::string& name, const bool bool_value); Parameter(const std::string& name, const int int_value); Parameter(const std::string& name, const int64_t int_value); Parameter(const std::string& name, const float double_value); Parameter(const std::string& name, const double double_value); Parameter(const std::string& name, const std::string& string_value); Parameter(const std::string& name, const char* string_value); Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc); Parameter(const std::string& name, const google::protobuf::Message& msg); ``` ### API List - Reading parameters ```cpp inline ParamType type() const; inline std::string TypeName() const; inline std::string Descriptor() const; inline const std::string Name() const; inline bool AsBool() const; inline int64_t AsInt64() const; inline double AsDouble() const; inline const std::string AsString() const; std::string DebugString() const; template <typename Type> typename std::enable_if<std::is_base_of<google::protobuf::Message, Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_integral<Type>::value && !std::is_same<Type, bool>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_floating_point<Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_convertible<Type, std::string>::value, const std::string&>::type value() const; template <typename Type> typename std::enable_if<std::is_same<Type, bool>::value, bool>::type value() const; ``` ### API List - Creating parameter service ```cpp explicit ParameterService(const std::shared_ptr<Node>& node); void SetParameter(const Parameter& parameter); bool GetParameter(const std::string& param_name, Parameter* parameter); bool ListParameters(std::vector<Parameter>* parameters); ``` ### API List - Creating parameter client ```cpp ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name); bool SetParameter(const Parameter& parameter); bool GetParameter(const std::string& param_name, Parameter* parameter); bool ListParameters(std::vector<Parameter>* parameters); ``` ## Timer API You can set the parameters of the Timer and call the start and stop interfaces to start the timer and stop the timer. For additional information and examples, refer to [Timer](#timer) ### API List ```cpp Timer(uint32_t period, std::function<void()> callback, bool oneshot); Timer(TimerOption opt); void SetTimerOption(TimerOption opt); void Start(); void Stop(); ``` ## Time API For additional information and examples, refer to [Time](#use-of-time) ### API List ```cpp static const Time MAX; static const Time MIN; Time() {} explicit Time(uint64_t nanoseconds); explicit Time(int nanoseconds); explicit Time(double seconds); Time(uint32_t seconds, uint32_t nanoseconds); Time(const Time& other); static Time Now(); static Time MonoTime(); static void SleepUntil(const Time& time); double ToSecond() const; uint64_t ToNanosecond() const; std::string ToString() const; bool IsZero() const; ``` ## Duration API Interval-related interface, used to indicate the time interval, can be initialized according to the specified nanosecond or second. ### API List ```cpp Duration() {} Duration(int64_t nanoseconds); Duration(int nanoseconds); Duration(double seconds); Duration(uint32_t seconds, uint32_t nanoseconds); Duration(const Rate& rate); Duration(const Duration& other); double ToSecond() const; int64_t ToNanosecond() const; bool IsZero() const; void Sleep() const; ``` ## Rate API The frequency interface is generally used to initialize the time of the sleep frequency after the object is initialized according to the specified frequency. ### API List ```cpp Rate(double frequency); Rate(uint64_t nanoseconds); Rate(const Duration&); void Sleep(); void Reset(); Duration CycleTime() const; Duration ExpectedCycleTime() const { return expected_cycle_time_; } ``` ## RecordReader API The interface for reading the record file is used to read the message and channel information in the record file. ### API List ```cpp RecordReader(); bool Open(const std::string& filename, uint64_t begin_time = 0, uint64_t end_time = UINT64_MAX); void Close(); bool ReadMessage(); bool EndOfFile(); const std::string& CurrentMessageChannelName(); std::shared_ptr<RawMessage> CurrentRawMessage(); uint64_t CurrentMessageTime(); ``` ## RecordWriter API The interface for writing the record file, used to record the message and channel information into the record file. ### API List ```cpp RecordWriter(); bool Open(const std::string& file); void Close(); bool WriteChannel(const std::string& name, const std::string& type, const std::string& proto_desc); template <typename MessageT> bool WriteMessage(const std::string& channel_name, const MessageT& message, const uint64_t time_nanosec, const std::string& proto_desc = ""); bool SetSizeOfFileSegmentation(uint64_t size_kilobytes); bool SetIntervalOfFileSegmentation(uint64_t time_sec); ```
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Migration_Guide.md
Migration guide from Apollo ROS ================================ This article describes the essential changes for projects to migrate from Apollo ROS (Apollo 3.0 and before) to Apollo Cyber RT (Apollo 3.5 and after). We will be using the very first ROS project talker/listener as example to demonstrate step by step migration instruction. ## Build system ROS use `CMake` as its build system but Cyber RT use `bazel`. In a ROS project, CmakeLists.txt and package.xml are required for defining build configs like build target, dependency, message files and so on. As for a Cyber RT component, a single bazel BUILD file covers. Some key build config mappings are listed below. Cmake ``` cmake project(pb_msgs_example) add_proto_files( DIRECTORY proto FILES chatter.proto ) ## Declare a C++ executable add_executable(pb_talker src/talker.cpp) target_link_libraries(pb_talker ${catkin_LIBRARIES}pb_msgs_example_proto) add_executable(pb_listener src/listener.cpp) target_link_libraries(pb_listener ${catkin_LIBRARIES} pb_msgs_example_proto) ``` Bazel ```python cc_binary( name = "talker", srcs = ["talker.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "listener", srcs = ["listener.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` We can find the mapping easily from the 2 file snippets. For example, `pb_talker` and `src/talker.cpp` in cmake `add_executable` setting map to `name = "talker"` and `srcs = ["talker.cc"]` in BUILD file `cc_binary`. ### Proto Apollo ROS has customized to support proto message formate that a separate section `add_proto_files` and projectName_proto(`pb_msgs_example_proto`) in `target_link_libraries` are required to send message in proto formate. For config proto message in Cyber RT, it's as simple as adding the target proto file path concantenated with name of `cc_proto_library` in `deps` setting. The `cc_proto_library` is set up in BUILD file under proto folder. ```python cc_proto_library( name = "examples_cc_proto", deps = [ ":examples_proto", ], ) proto_library( name = "examples_proto", srcs = [ "examples.proto", ], ) ``` The package definition has also changed in Cyber RT. In Apollo ROS a fixed package `package pb_msgs;` is used for proto files, but in Cyber RT, the proto file path `package apollo.cyber.examples.proto;` is used instead. ## Folder structure As shown below, Cyber RT remove the src folder and pull all source code in the same folder as BUILD file. BUILD file plays the same role as CMakeLists.txt plus package.xml. Both Cyber RT and Apollo ROS talker/listener example have a proto folder for message proto files but Cyber RT requires a separate BUILD file for proto folder to set up the proto library. ### Apollo ROS - CMakeLists.txt - package.xml - proto - chatter.proto - src - listener.cpp - talker.cpp ### Cyber RT - BUILD - listener.cc - talker.cc - proto - BUILD - examples.proto (with chatter message) ## Update source code ### Listener Cyber RT ```cpp #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" void MessageCallback( const std::shared_ptr<apollo::cyber::examples::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char* argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cyber::examples::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; } ``` ROS ```cpp #include "ros/ros.h" #include "chatter.pb.h" void MessageCallback(const boost::shared_ptr<pb_msgs::Chatter>& msg) { ROS_INFO_STREAM("Time: " << msg->stamp().sec() << "." << msg->stamp().nsec()); ROS_INFO("I heard pb Chatter message: [%s]", msg->content().c_str()); } int main(int argc, char** argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber pb_sub = n.subscribe("chatter", 1000, MessageCallback); ros::spin(); return 0; } ``` You can see easily from the two listener code above that Cyber RT provides very similar API to for developers to migrate from ROS. - `ros::init(argc, argv, "listener");` --> `apollo::cyber::Init(argv[0]);` - `ros::NodeHandle n;` --> `auto listener_node = apollo::cyber::CreateNode("listener");` - `ros::Subscriber pb_sub = n.subscribe("chatter", 1000, MessageCallback);` --> `auto listener = listener_node->CreateReader("channel/chatter", MessageCallback);` - `ros::spin();` --> `apollo::cyber::WaitForShutdown();` Note: for Cyber RT, a listener node has to use `node->CreateReader<messageType>(channelName, callback)` to read data from channel. ### Talker Cyber RT ```cpp #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Chatter; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node auto talker_node = apollo::cyber::CreateNode("talker"); // create talker auto talker = talker_node->CreateWriter<Chatter>("channel/chatter"); Rate rate(1.0); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<Chatter>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_lidar_timestamp(Time::Now().ToNanosecond()); msg->set_seq(seq++); msg->set_content("Hello, apollo!"); talker->Write(msg); AINFO << "talker sent a message!"; rate.Sleep(); } return 0; } ``` ROS ```cpp #include "ros/ros.h" #include "chatter.pb.h" #include <sstream> int main(int argc, char** argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<pb_msgs::Chatter>("chatter", 1000); ros::Rate loop_rate(10); int count = 0; while (ros::ok()) { pb_msgs::Chatter msg; ros::Time now = ros::Time::now(); msg.mutable_stamp()->set_sec(now.sec); msg.mutable_stamp()->set_nsec(now.nsec); std::stringstream ss; ss << "Hello world " << count; msg.set_content(ss.str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; } ``` Most of the mappings are illustrated in listener code above, the rest are listed here. - `ros::Publisher chatter_pub = n.advertise<pb_msgs::Chatter>("chatter", 1000);` --> `auto talker = talker_node->CreateWriter<Chatter>("channel/chatter");` - `chatter_pub.publish(msg);` --> ` talker->Write(msg);` ## Tools mapping ROS | Cyber RT | Note :------------- | :------------- | :-------------- rosbag | cyber_recorder | data file scripts/diagnostics.sh | cyber_monitor | channel debug offline_lidar_visualizer_tool | cyber_visualizer |point cloud visualizer ## ROS bag data migration The data file changed from ROS bag to Cyber record in Cyber RT. Cyber RT has a data migration tool `rosbag_to_record` for users to easily migrate data files before Apollo 3.0 (ROS) to Cyber RT like the sample usage below. ```bash rosbag_to_record demo_3.0.bag demo_3.5.record ```
0
apollo_public_repos/apollo/cyber/doxy-docs
apollo_public_repos/apollo/cyber/doxy-docs/source/CyberRT_Quick_Start.md
# How to Create and Run a new Component in Cyber RT Apollo Cyber RT framework is built upon the concept of components. As the building block of Cyber RT, each component is a specific algorithm module which processes a set of inputs and generates its set of outputs. To successfully create and launch a new component, there are basically 4 steps: - Set up directory layout - Implement the component class - Configuration setup - Launch the component The example below demonstrates how to create, build and run a simple component named `CommonComponentExample`. To explore more about Cyber RT, you can find a couple of examples showing different functionalities of Cyber RT under the `cyber/examples` directory. > **Note**: The examples need to run after successfully built within Apollo > Docker container. ## Set up directry layout Take the sample component under `cyber/examples/common_component_example` for example: - Header file: common_component_example.h - Source file: common_component_example.cc - BUILD file: BUILD - DAG file: common.dag - Launch file: common.launch ## Implement the sample component class ### Header file In the header file (`common_component_example.h`) for the sample component: - Inherit the `Component` base class - Define your own `Init` and `Proc` functions. Please note that for `proc`, input data types need to be specified also. - Register the sample component class to be globally visible using the `CYBER_REGISTER_COMPONENT` macro. ```cpp #include <memory> #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::examples::proto::Driver; class CommonComponentSample : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(CommonComponentSample) ``` ### Source File Implement both the `Init` and `Proc` functions in `common_component_example.cc`: ```cpp #include "cyber/examples/common_component_example/common_component_example.h" bool CommonComponentSample::Init() { AINFO << "Commontest component init"; return true; } bool CommonComponentSample::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start common component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; } ``` ### BUILD file ```python load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "libcommon_component_example.so", linkshared = True, linkstatic = False, deps = [":common_component_example_lib"], ) cc_library( name = "common_component_example_lib", srcs = ["common_component_example.cc"], hdrs = ["common_component_example.h"], visibility = ["//visibility:private"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cpplint() ``` ## Configuration setup ### DAG file To configure the DAG file (`common.dag` here), specify the following items: - Channel names: for data input and output - Library path: library built from component class - Class name: the class name of the component ```protobuf # Define all components in DAG streaming. module_config { module_library : "/apollo/bazel-bin/cyber/examples/common_component_example/libcommon_component_example.so" components { class_name : "CommonComponentSample" config { name : "common" readers { channel: "/apollo/prediction" } readers { channel: "/apollo/test" } } } } ``` ### Launch file To configure the launch (`common.launch`) file, specify the following items: - The name of the component - The DAG file created in the previous step - The name of the process to run the component ```xml <cyber> <component> <name>common</name> <dag_conf>/apollo/cyber/examples/common_component_example/common.dag</dag_conf> <process_name>common</process_name> </component> </cyber> ``` ## Launch the component ### Build Build the sample component by running the command below: ```bash cd /apollo bash apollo.sh build ``` ### Environment setup Then configure the environment: ```bash source cyber/setup.bash # To see output from terminal export GLOG_alsologtostderr=1 ``` ### Launch the component You can choose either of the two ways to launch the newly built component: - Launch with the launch file (recommended) ```bash cyber_launch start cyber/examples/common_component_example/common.launch ``` - Launch with the DAG file ```bash mainboard -d cyber/examples/common_component_example/common.dag ``` ### _Feed_ channel data for the component to process Open another terminal: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_test_writer ``` Open the 3rd terminal and run: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_prediction_writer ``` And you should see output from terminal #1 like the following: ``` I0331 16:49:34.736016 1774773 common_component_example.cc:25] [mainboard]Start common component Proc [1094] [766] I0331 16:49:35.069005 1774775 common_component_example.cc:25] [mainboard]Start common component Proc [1095] [767] I0331 16:49:35.402289 1774783 common_component_example.cc:25] [mainboard]Start common component Proc [1096] [768] ```
0
apollo_public_repos/apollo/cyber/doxy-docs/source
apollo_public_repos/apollo/cyber/doxy-docs/source/api/pythonapi.rst
python/cyber_py/cyber.py ============================ Defined in python/cyber_py/cyber.py .. doxygenfunction:: cyber_py::cyber::init :project: Cyber RT Documents .. doxygenfunction:: cyber_py::cyber::ok :project: Cyber RT Documents .. doxygenfunction:: cyber_py::cyber::shutdown :project: Cyber RT Documents .. doxygenfunction:: cyber_py::cyber::is_shutdown :project: Cyber RT Documents .. doxygenfunction:: cyber_py::cyber::waitforshutdown :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::Node :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::Writer :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::Reader :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::Client :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::ChannelUtils :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber::NodeUtils :members: :project: Cyber RT Documents python/cyber_py/record.py ================================ Defined in python/cyber_py/record.py .. doxygenclass:: cyber_py::record::RecordReader :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::record::RecordWriter :members: :project: Cyber RT Documents python/cyber_py/cyber_time.py ================================= Defined in python/cyber_py/cyber_time.py .. doxygenclass:: cyber_py::cyber_time::Duration :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber_time::Time :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::cyber_time::Rate :members: :project: Cyber RT Documents python/cyber_py/cyber_timer.py ================================== Defined in python/cyber_py/cyber_timer.py .. doxygenclass:: cyber_py::cyber_timer::Timer :members: :project: Cyber RT Documents python/cyber_py/parameter.py =============================== Defined in python/cyber_py/parameter.py .. doxygenclass:: cyber_py::parameter::Parameter :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::parameter::ParameterServer :members: :project: Cyber RT Documents .. doxygenclass:: cyber_py::parameter::ParameterClient :members: :project: Cyber RT Documents
0
apollo_public_repos/apollo/cyber/doxy-docs/source
apollo_public_repos/apollo/cyber/doxy-docs/source/api/pythonapi_index.rst
Python API ==================== Cyber RT provides the python interfaces for developers. .. toctree:: pythonapi
0
apollo_public_repos/apollo/cyber/doxy-docs/source
apollo_public_repos/apollo/cyber/doxy-docs/source/api/cppapi_index.rst
C++ API ==================== Topological communication APIs is actually implemented in ``node`` and ``reader/writer`` and ``client/service``. .. toctree:: cppapi
0
apollo_public_repos/apollo/cyber/doxy-docs/source
apollo_public_repos/apollo/cyber/doxy-docs/source/api/cppapi.rst
cyber/node/node.h =================== Defined in ``cyber/node/node.h`` .. doxygenclass:: apollo::cyber::Node :members: :project: Cyber RT Documents cyber/node/reader_base.h ========================== Defined in ``cyber/node/reader_base.h`` .. doxygenclass:: apollo::cyber::ReaderBase :members: :project: Cyber RT Documents cyber/node/reader.h ===================== Defined in ``cyber/node/reader.h`` .. doxygenclass:: apollo::cyber::Reader :members: :project: Cyber RT Documents cyber/node/writer_base.h ========================== Defined in ``cyber/node/writer_base.h`` .. doxygenclass:: apollo::cyber::WriterBase :members: :project: Cyber RT Documents cyber/node/writer.h ===================== Defined in ``cyber/node/writer.h`` .. doxygenclass:: apollo::cyber::Writer :members: :project: Cyber RT Documents cyber/node/node_channel_impl.h ================================ Defined in ``cyber/node/node_channel_impl.h`` .. doxygenstruct:: apollo::cyber::ReaderConfig :members: :project: Cyber RT Documents .. doxygenclass:: apollo::cyber::NodeChannelImpl :members: :project: Cyber RT Documents cyber/node/node_service_impl.h ================================ Defined in ``cyber/node/node_service_impl.h`` .. doxygenclass:: apollo::cyber::NodeServiceImpl :members: :project: Cyber RT Documents cyber/parameter/parameter.h ============================= Defined in ``cyber/parameter/parameter.h`` .. doxygenclass:: apollo::cyber::Parameter :members: :project: Cyber RT Documents cyber/parameter/parameter_server.h ==================================== Defined in ``cyber/parameter/parameter_server.h`` .. doxygenclass:: apollo::cyber::ParameterServer :members: :project: Cyber RT Documents cyber/parameter/parameter_client.h ==================================== Defined in ``cyber/parameter/parameter_client.h`` .. doxygenclass:: apollo::cyber::ParameterClient :members: :project: Cyber RT Documents cyber/service/service_base.h ============================== Defined in ``cyber/service/service_base.h`` .. doxygenclass:: apollo::cyber::ServiceBase :members: :project: Cyber RT Documents cyber/service/service.h ========================= Defined in ``cyber/service/service.h`` .. doxygenclass:: apollo::cyber::Service :members: :project: Cyber RT Documents cyber/service/client_base.h ============================= Defined in ``cyber/service/client_base.h`` .. doxygenclass:: apollo::cyber::ClientBase :members: :project: Cyber RT Documents cyber/service/client.h ======================== Defined in ``cyber/service/client.h`` .. doxygenclass:: apollo::cyber::Client :members: :project: Cyber RT Documents cyber/service_discovery/specific_manager/manager.h ==================================================== Defined in ``cyber/service_discovery/specific_manager/channel_namager.h`` .. doxygenclass:: apollo::cyber::service_discovery::Manager :members: :project: Cyber RT Documents cyber/service_discovery/specific_manager/channel_manager.h ============================================================ Defined in ``cyber/service_discovery/specific_manager/channel_manager.h`` .. doxygenclass:: apollo::cyber::service_discovery::ChannelManager :members: :project: Cyber RT Documents cyber/service_discovery/specific_manager/node_manager.h ========================================================= Defined in ``cyber/service_discovery/specific_manager/node_manager.h`` .. doxygenclass:: apollo::cyber::service_discovery::NodeManager :members: :project: Cyber RT Documents cyber/service_discovery/specific_manager/service_manager.h ============================================================ Defined in ``cyber/service_discovery/specific_manager/service_manager.h`` .. doxygenclass:: apollo::cyber::service_discovery::ServiceManager :members: :project: Cyber RT Documents cyber/service_discovery/topology_manager.h ============================================ Defined in ``cyber/service_discovery/topology_manager.h`` .. doxygenclass:: apollo::cyber::service_discovery::TopologyManager :members: :project: Cyber RT Documents cyber/component/component.h ============================= Defined in ``cyber/component/component.h`` .. doxygenclass:: apollo::cyber::Component :members: :project: Cyber RT Documents cyber/component/timer_component.h ====================================== Defined in ``cyber/component/timer_component.h`` .. doxygenclass:: apollo::cyber::TimerComponent :members: :project: Cyber RT Documents cyber/logger/async_logger.h ============================ Defined in ``cyber/logger/async_logger.h`` .. doxygenclass:: apollo::cyber::logger::AsyncLogger :members: :project: Cyber RT Documents cyber/timer/timer.h ==================== Defined in ``cyber/timer/timer.h`` .. doxygenstruct:: apollo::cyber::TimerOption :members: :project: Cyber RT Documents .. doxygenclass:: apollo::cyber::Timer :members: :project: Cyber RT Documents cyber/time/time.h ==================== Defined in ``cyber/time/time.h`` .. doxygenclass:: apollo::cyber::Time :members: :project: Cyber RT Documents cyber/record/header_builder.h ================================= Defined in ``cyber/record/header_builder.h`` .. doxygenclass:: apollo::cyber::record::HeaderBuilder :members: :project: Cyber RT Documents cyber/record/record_base.h ================================= Defined in ``cyber/record/record_base.h`` .. doxygenclass:: apollo::cyber::record::RecordBase :members: :project: Cyber RT Documents cyber/record/record_message.h ================================= Defined in ``cyber/record/record_message.h`` .. doxygenstruct:: apollo::cyber::record::RecordMessage :members: :project: Cyber RT Documents cyber/record/record_reader.h ================================= Defined in ``cyber/record/record_reader.h`` .. doxygenclass:: apollo::cyber::record::RecordReader :members: :project: Cyber RT Documents cyber/record/record_writer.h ================================= Defined in ``cyber/record/record_writer.h`` .. doxygenclass:: apollo::cyber::record::RecordWriter :members: :project: Cyber RT Documents cyber/record/record_viewer.h ================================= Defined in ``cyber/record/record_viewer.h`` .. doxygenclass:: apollo::cyber::record::RecordViewer :members: :project: Cyber RT Documents
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/sysmo/sysmo_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/sysmo/sysmo.h" #include <cstdlib> #include <thread> #include "gtest/gtest.h" #include "cyber/common/environment.h" #include "cyber/scheduler/scheduler_factory.h" namespace apollo { namespace cyber { using apollo::cyber::common::GetEnv; TEST(SysMoTest, cases) { auto sched = scheduler::Instance(); setenv("sysmo_start", "1", 1); auto sysmo_start = GetEnv("sysmo_start"); EXPECT_EQ(sysmo_start, "1"); auto sysmo = SysMo::Instance(); std::this_thread::sleep_for(std::chrono::milliseconds(300)); sysmo->Shutdown(); sched->Shutdown(); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/sysmo/sysmo.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/sysmo/sysmo.h" #include "cyber/common/environment.h" namespace apollo { namespace cyber { using apollo::cyber::common::GetEnv; SysMo::SysMo() { Start(); } void SysMo::Start() { auto sysmo_start = GetEnv("sysmo_start"); if (sysmo_start != "" && std::stoi(sysmo_start)) { start_ = true; sysmo_ = std::thread(&SysMo::Checker, this); } } void SysMo::Shutdown() { if (!start_ || shut_down_.exchange(true)) { return; } cv_.notify_all(); if (sysmo_.joinable()) { sysmo_.join(); } } void SysMo::Checker() { while (cyber_unlikely(!shut_down_.load())) { scheduler::Instance()->CheckSchedStatus(); std::unique_lock<std::mutex> lk(lk_); cv_.wait_for(lk, std::chrono::milliseconds(sysmo_interval_ms_)); } } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/sysmo/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_sysmo_hdrs", srcs = glob([ "*.h", ]), ) cc_test( name = "sysmo_test", size = "small", srcs = ["sysmo_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "sysmo", srcs = ["sysmo.cc"], hdrs = ["sysmo.h"], deps = [ "//cyber/scheduler:scheduler_factory", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/sysmo/sysmo.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_SYSMO_SYSMO_H_ #define CYBER_SYSMO_SYSMO_H_ #include <chrono> #include <condition_variable> #include <list> #include <mutex> #include <string> #include <thread> #include "cyber/scheduler/scheduler_factory.h" namespace apollo { namespace cyber { using apollo::cyber::scheduler::Scheduler; class SysMo { public: void Start(); void Shutdown(); private: void Checker(); std::atomic<bool> shut_down_{false}; bool start_ = false; int sysmo_interval_ms_ = 100; std::condition_variable cv_; std::mutex lk_; std::thread sysmo_; DECLARE_SINGLETON(SysMo); }; } // namespace cyber } // namespace apollo #endif // CYBER_SYSMO_SYSMO_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/listener.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/examples/proto/examples.pb.h" #include "cyber/cyber.h" void MessageCallback( const std::shared_ptr<apollo::cyber::examples::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char* argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cyber::examples::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/record.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <string> #include "cyber/proto/record.pb.h" #include "cyber/cyber.h" #include "cyber/message/raw_message.h" #include "cyber/record/record_message.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" using apollo::cyber::message::RawMessage; using ::apollo::cyber::record::RecordMessage; using ::apollo::cyber::record::RecordReader; using ::apollo::cyber::record::RecordWriter; const char CHANNEL_NAME_1[] = "/test/channel1"; const char CHANNEL_NAME_2[] = "/test/channel2"; const char MESSAGE_TYPE_1[] = "apollo.cyber.proto.Test"; const char MESSAGE_TYPE_2[] = "apollo.cyber.proto.Channel"; const char PROTO_DESC[] = "1234567890"; const char STR_10B[] = "1234567890"; const char TEST_FILE[] = "test.record"; void test_write(const std::string &writefile) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(writefile); writer.WriteChannel(CHANNEL_NAME_1, MESSAGE_TYPE_1, PROTO_DESC); for (uint32_t i = 0; i < 100; ++i) { auto msg = std::make_shared<RawMessage>("abc" + std::to_string(i)); writer.WriteMessage(CHANNEL_NAME_1, msg, 888 + i); } writer.Close(); } void test_read(const std::string &readfile) { RecordReader reader(readfile); RecordMessage message; uint64_t msg_count = reader.GetMessageNumber(CHANNEL_NAME_1); AINFO << "MSGTYPE: " << reader.GetMessageType(CHANNEL_NAME_1); AINFO << "MSGDESC: " << reader.GetProtoDesc(CHANNEL_NAME_1); // read all message uint64_t i = 0; uint64_t valid = 0; for (i = 0; i < msg_count; ++i) { if (reader.ReadMessage(&message)) { AINFO << "msg[" << i << "]-> " << "channel name: " << message.channel_name << "; content: " << message.content << "; msg time: " << message.time; valid++; } else { AERROR << "read msg[" << i << "] failed"; } } AINFO << "static msg================="; AINFO << "MSG validmsg:totalcount: " << valid << ":" << msg_count; } int main(int argc, char *argv[]) { apollo::cyber::Init(argv[0]); test_write(TEST_FILE); sleep(1); test_read(TEST_FILE); return 0; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/paramserver.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/cyber.h" #include "cyber/parameter/parameter_client.h" #include "cyber/parameter/parameter_server.h" using apollo::cyber::Parameter; using apollo::cyber::ParameterClient; using apollo::cyber::ParameterServer; int main(int argc, char** argv) { apollo::cyber::Init(*argv); std::shared_ptr<apollo::cyber::Node> node = apollo::cyber::CreateNode("parameter"); auto param_server = std::make_shared<ParameterServer>(node); auto param_client = std::make_shared<ParameterClient>(node, "parameter"); param_server->SetParameter(Parameter("int", 1)); Parameter parameter; param_server->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); param_client->SetParameter(Parameter("string", "test")); param_client->GetParameter("string", &parameter); AINFO << "string: " << parameter.AsString(); param_client->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); return 0; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/service.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/examples/proto/examples.pb.h" #include "cyber/cyber.h" using apollo::cyber::examples::proto::Driver; int main(int argc, char* argv[]) { apollo::cyber::Init(argv[0]); std::shared_ptr<apollo::cyber::Node> node( apollo::cyber::CreateNode("start_node")); auto server = node->CreateService<Driver, Driver>( "test_server", [](const std::shared_ptr<Driver>& request, std::shared_ptr<Driver>& response) { AINFO << "server: i am driver server"; static uint64_t id = 0; ++id; response->set_msg_id(id); response->set_timestamp(0); }); auto client = node->CreateClient<Driver, Driver>("test_server"); auto driver_msg = std::make_shared<Driver>(); driver_msg->set_msg_id(0); driver_msg->set_timestamp(0); while (apollo::cyber::OK()) { auto res = client->SendRequest(driver_msg); if (res != nullptr) { AINFO << "client: responese: " << res->ShortDebugString(); } else { AINFO << "client: service may not ready."; } sleep(1); } apollo::cyber::WaitForShutdown(); return 0; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "talker", srcs = ["talker.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "listener", srcs = ["listener.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) install( name = "install", targets = [ ":talker", ":listener", ], runtime_dest = "cyber/examples", deps = [ "//cyber/examples/common_component_example:install", "//cyber/examples/timer_component_example:install", "//cyber/examples/proto:cyber_examples_proto_hdrs", "//cyber/examples/proto:cyber_examples_proto_so", ], ) cc_binary( name = "paramserver", srcs = ["paramserver.cc"], deps = [ "//cyber", ], ) cc_binary( name = "service", srcs = ["service.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "record", srcs = ["record.cc"], deps = [ "//cyber", "//cyber/proto:record_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/examples/talker.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/examples/proto/examples.pb.h" #include "cyber/cyber.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::cyber::examples::proto::Chatter; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node auto talker_node = apollo::cyber::CreateNode("talker"); // create talker auto talker = talker_node->CreateWriter<Chatter>("channel/chatter"); Rate rate(1.0); uint64_t seq = 0; while (apollo::cyber::OK()) { auto msg = std::make_shared<Chatter>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_lidar_timestamp(Time::Now().ToNanosecond()); msg->set_seq(seq); msg->set_content("Hello, apollo!"); talker->Write(msg); AINFO << "talker sent a message! No. " << seq; seq++; rate.Sleep(); } return 0; }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/proto/examples.proto
syntax = "proto2"; package apollo.cyber.examples.proto; message SamplesTest1 { optional string class_name = 1; optional string case_name = 2; }; message Chatter { optional uint64 timestamp = 1; optional uint64 lidar_timestamp = 2; optional uint64 seq = 3; optional bytes content = 4; }; message Driver { optional string content = 1; optional uint64 msg_id = 2; optional uint64 timestamp = 3; };
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") load("//tools:cc_so_proto_rules.bzl", "cc_so_proto_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) install_files( name = "cyber_examples_proto_hdrs", dest = "cyber/include/proto", files = [ ":examples_cc_proto_hdrs", ], ) install( name = "cyber_examples_proto_so", library_dest = "cyber/lib", targets = [ ":libexamples_cc_proto.so", ], ) cc_so_proto_library( name = "examples_cc_proto", srcs = [ ":examples_proto", ], ) proto_library( name = "examples_proto", srcs = ["examples.proto"], ) py_proto_library( name = "examples_py_pb2", deps = [ ":examples_proto", ], )
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/common.launch
<cyber> <module> <name>common</name> <dag_conf>/apollo/cyber/examples/common_component_example/common.dag</dag_conf> <process_name>common</process_name> </module> </cyber>
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/common_component_example.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/examples/common_component_example/common_component_example.h" bool CommonComponentSample::Init() { AINFO << "Commontest component init"; return true; } bool CommonComponentSample::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start common component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/channel_prediction_writer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::cyber::examples::proto::Driver; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node auto talker_node = apollo::cyber::CreateNode("prediction_writer"); // create talker auto talker = talker_node->CreateWriter<Driver>("/apollo/prediction"); Rate rate(3.0); std::string content("apollo_prediction"); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<Driver>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_msg_id(seq++); msg->set_content(content + std::to_string(seq - 1)); talker->Write(msg); AINFO << "/apollo/prediction sent message, seq=" << (seq - 1) << ";"; rate.Sleep(); } return 0; }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/README.md
# Common Component Example of the CyberRT framework ## How to Build ``` ./apollo.sh build cyber ``` Or if you use Bazel directly, ``` bazel build //cyber/examples/common_component_example/... ``` ## How to Run ### Enable logging to stderr - Change `GLOG_alsologtostderr` from `0` to `1` in `cyber/setup.bash` - Run `source cyber/setup.bash` in current console. ``` export GLOG_alsologtostderr=1 ``` ### Start the sample component ``` cyber_launch start cyber/examples/common_component_example/common.launch ``` Or ``` mainboard -d cyber/examples/common_component_example/common.dag ``` ### Start the writer nodes Open two more terminals, run the following commands respectively. ``` bazel run //cyber/examples/common_component_example:channel_test_writer ``` and ... ``` bazel run //cyber/examples/common_component_example:channel_prediction_writer ``` Now you should see console output of the `CommonComponentSample` example from the first terminal.
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/common_component_example.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <memory> #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::examples::proto::Driver; class CommonComponentSample : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(CommonComponentSample)
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "libcommon_component_example.so", linkshared = True, linkstatic = True, deps = [":common_component_example_lib"], ) cc_library( name = "common_component_example_lib", srcs = ["common_component_example.cc"], hdrs = ["common_component_example.h"], visibility = ["//visibility:private"], alwayslink = True, deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "channel_test_writer", srcs = ["channel_test_writer.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "channel_prediction_writer", srcs = ["channel_prediction_writer.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) filegroup( name = "conf", srcs = [ ":common.dag", ":common.launch", ], ) install( name = "install", data = [ ":conf", ], # We want to install channel_*_writer into runtime_dest # rather than bin/ runtime_dest = "cyber/examples/common_component_example", targets = [ ":channel_prediction_writer", ":channel_test_writer", ":libcommon_component_example.so", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/channel_test_writer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::cyber::examples::proto::Driver; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node auto talker_node = apollo::cyber::CreateNode("channel_test_writer"); // create talker auto talker = talker_node->CreateWriter<Driver>("/apollo/test"); Rate rate(2.0); std::string content("apollo_test"); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<Driver>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_msg_id(seq++); msg->set_content(content + std::to_string(seq - 1)); talker->Write(msg); AINFO << "/apollo/test sent message, seq=" << (seq - 1) << ";"; rate.Sleep(); } return 0; }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/common_component_example/common.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/cyber/examples/common_component_example/libcommon_component_example.so" components { class_name : "CommonComponentSample" config { name : "common" readers { channel: "/apollo/prediction" } readers { channel: "/apollo/test" } } } }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/timer_component_example/timer.launch
<cyber> <module> <name>timer</name> <dag_conf>/apollo/cyber/examples/timer_component_example/timer.dag</dag_conf> <process_name>timer</process_name> </module> </cyber>
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/timer_component_example/timer_component_example.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <memory> #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/component/timer_component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::TimerComponent; using apollo::cyber::Writer; using apollo::cyber::examples::proto::Driver; class TimerComponentSample : public TimerComponent { public: bool Init() override; bool Proc() override; private: std::shared_ptr<Writer<Driver>> driver_writer_ = nullptr; }; CYBER_REGISTER_COMPONENT(TimerComponentSample)
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/timer_component_example/timer_component_example.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/examples/timer_component_example/timer_component_example.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" bool TimerComponentSample::Init() { driver_writer_ = node_->CreateWriter<Driver>("/carstatus/channel"); return true; } bool TimerComponentSample::Proc() { static int i = 0; auto out_msg = std::make_shared<Driver>(); out_msg->set_msg_id(i++); driver_writer_->Write(out_msg); AINFO << "timer_component_example: Write drivermsg->" << out_msg->ShortDebugString(); return true; }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/timer_component_example/timer.dag
module_config { module_library : "/apollo/bazel-bin/cyber/examples/timer_component_example/libtimer_component_example.so" timer_components { class_name : "TimerComponentSample" config { name : "timer" interval : 10 } } }
0
apollo_public_repos/apollo/cyber/examples
apollo_public_repos/apollo/cyber/examples/timer_component_example/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "libtimer_component_example.so", linkshared = True, linkstatic = True, deps = [":timer_component_example_lib"], ) cc_library( name = "timer_component_example_lib", srcs = ["timer_component_example.cc"], hdrs = ["timer_component_example.h"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], alwayslink = True, visibility = ["//visibility:private"], ) filegroup( name = "conf", srcs = [ ":timer.dag", ":timer.launch", ], ) install( name = "install", data = [ ":conf", ], targets = [ ":libtimer_component_example.so", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/croutine/croutine.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CROUTINE_CROUTINE_H_ #define CYBER_CROUTINE_CROUTINE_H_ #include <atomic> #include <chrono> #include <functional> #include <memory> #include <mutex> #include <set> #include <string> #include "cyber/common/log.h" #include "cyber/croutine/detail/routine_context.h" namespace apollo { namespace cyber { namespace croutine { using RoutineFunc = std::function<void()>; using Duration = std::chrono::microseconds; enum class RoutineState { READY, FINISHED, SLEEP, IO_WAIT, DATA_WAIT }; class CRoutine { public: explicit CRoutine(const RoutineFunc &func); virtual ~CRoutine(); // static interfaces static void Yield(); static void Yield(const RoutineState &state); static void SetMainContext(const std::shared_ptr<RoutineContext> &context); static CRoutine *GetCurrentRoutine(); static char **GetMainStack(); // public interfaces bool Acquire(); void Release(); // It is caller's responsibility to check if state_ is valid before calling // SetUpdateFlag(). void SetUpdateFlag(); // acquire && release should be called before Resume // when work-steal like mechanism used RoutineState Resume(); RoutineState UpdateState(); RoutineContext *GetContext(); char **GetStack(); void Run(); void Stop(); void Wake(); void HangUp(); void Sleep(const Duration &sleep_duration); // getter and setter RoutineState state() const; void set_state(const RoutineState &state); uint64_t id() const; void set_id(uint64_t id); const std::string &name() const; void set_name(const std::string &name); int processor_id() const; void set_processor_id(int processor_id); uint32_t priority() const; void set_priority(uint32_t priority); std::chrono::steady_clock::time_point wake_time() const; void set_group_name(const std::string &group_name) { group_name_ = group_name; } const std::string &group_name() { return group_name_; } private: CRoutine(CRoutine &) = delete; CRoutine &operator=(CRoutine &) = delete; std::string name_; std::chrono::steady_clock::time_point wake_time_ = std::chrono::steady_clock::now(); RoutineFunc func_; RoutineState state_; std::shared_ptr<RoutineContext> context_; std::atomic_flag lock_ = ATOMIC_FLAG_INIT; std::atomic_flag updated_ = ATOMIC_FLAG_INIT; bool force_stop_ = false; int processor_id_ = -1; uint32_t priority_ = 0; uint64_t id_ = 0; std::string group_name_; static thread_local CRoutine *current_routine_; static thread_local char *main_stack_; }; inline void CRoutine::Yield(const RoutineState &state) { auto routine = GetCurrentRoutine(); routine->set_state(state); SwapContext(GetCurrentRoutine()->GetStack(), GetMainStack()); } inline void CRoutine::Yield() { SwapContext(GetCurrentRoutine()->GetStack(), GetMainStack()); } inline CRoutine *CRoutine::GetCurrentRoutine() { return current_routine_; } inline char **CRoutine::GetMainStack() { return &main_stack_; } inline RoutineContext *CRoutine::GetContext() { return context_.get(); } inline char **CRoutine::GetStack() { return &(context_->sp); } inline void CRoutine::Run() { func_(); } inline void CRoutine::set_state(const RoutineState &state) { state_ = state; } inline RoutineState CRoutine::state() const { return state_; } inline std::chrono::steady_clock::time_point CRoutine::wake_time() const { return wake_time_; } inline void CRoutine::Wake() { state_ = RoutineState::READY; } inline void CRoutine::HangUp() { CRoutine::Yield(RoutineState::DATA_WAIT); } inline void CRoutine::Sleep(const Duration &sleep_duration) { wake_time_ = std::chrono::steady_clock::now() + sleep_duration; CRoutine::Yield(RoutineState::SLEEP); } inline uint64_t CRoutine::id() const { return id_; } inline void CRoutine::set_id(uint64_t id) { id_ = id; } inline const std::string &CRoutine::name() const { return name_; } inline void CRoutine::set_name(const std::string &name) { name_ = name; } inline int CRoutine::processor_id() const { return processor_id_; } inline void CRoutine::set_processor_id(int processor_id) { processor_id_ = processor_id; } inline RoutineState CRoutine::UpdateState() { // Synchronous Event Mechanism if (state_ == RoutineState::SLEEP && std::chrono::steady_clock::now() > wake_time_) { state_ = RoutineState::READY; return state_; } // Asynchronous Event Mechanism if (!updated_.test_and_set(std::memory_order_release)) { if (state_ == RoutineState::DATA_WAIT || state_ == RoutineState::IO_WAIT) { state_ = RoutineState::READY; } } return state_; } inline uint32_t CRoutine::priority() const { return priority_; } inline void CRoutine::set_priority(uint32_t priority) { priority_ = priority; } inline bool CRoutine::Acquire() { return !lock_.test_and_set(std::memory_order_acquire); } inline void CRoutine::Release() { return lock_.clear(std::memory_order_release); } inline void CRoutine::SetUpdateFlag() { updated_.clear(std::memory_order_release); } } // namespace croutine } // namespace cyber } // namespace apollo #endif // CYBER_CROUTINE_CROUTINE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/croutine/routine_factory.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CROUTINE_ROUTINE_FACTORY_H_ #define CYBER_CROUTINE_ROUTINE_FACTORY_H_ #include <memory> #include <utility> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/croutine/croutine.h" #include "cyber/data/data_visitor.h" #include "cyber/event/perf_event_cache.h" namespace apollo { namespace cyber { namespace croutine { class RoutineFactory { public: using VoidFunc = std::function<void()>; using CreateRoutineFunc = std::function<VoidFunc()>; // We can use routine_func directly. CreateRoutineFunc create_routine; inline std::shared_ptr<data::DataVisitorBase> GetDataVisitor() const { return data_visitor_; } inline void SetDataVisitor(const std::shared_ptr<data::DataVisitorBase>& dv) { data_visitor_ = dv; } private: std::shared_ptr<data::DataVisitorBase> data_visitor_ = nullptr; }; template <typename M0, typename F> RoutineFactory CreateRoutineFactory( F&& f, const std::shared_ptr<data::DataVisitor<M0>>& dv) { RoutineFactory factory; factory.SetDataVisitor(dv); factory.create_routine = [=]() { return [=]() { std::shared_ptr<M0> msg; for (;;) { CRoutine::GetCurrentRoutine()->set_state(RoutineState::DATA_WAIT); if (dv->TryFetch(msg)) { f(msg); CRoutine::Yield(RoutineState::READY); } else { CRoutine::Yield(); } } }; }; return factory; } template <typename M0, typename M1, typename F> RoutineFactory CreateRoutineFactory( F&& f, const std::shared_ptr<data::DataVisitor<M0, M1>>& dv) { RoutineFactory factory; factory.SetDataVisitor(dv); factory.create_routine = [=]() { return [=]() { std::shared_ptr<M0> msg0; std::shared_ptr<M1> msg1; for (;;) { CRoutine::GetCurrentRoutine()->set_state(RoutineState::DATA_WAIT); if (dv->TryFetch(msg0, msg1)) { f(msg0, msg1); CRoutine::Yield(RoutineState::READY); } else { CRoutine::Yield(); } } }; }; return factory; } template <typename M0, typename M1, typename M2, typename F> RoutineFactory CreateRoutineFactory( F&& f, const std::shared_ptr<data::DataVisitor<M0, M1, M2>>& dv) { RoutineFactory factory; factory.SetDataVisitor(dv); factory.create_routine = [=]() { return [=]() { std::shared_ptr<M0> msg0; std::shared_ptr<M1> msg1; std::shared_ptr<M2> msg2; for (;;) { CRoutine::GetCurrentRoutine()->set_state(RoutineState::DATA_WAIT); if (dv->TryFetch(msg0, msg1, msg2)) { f(msg0, msg1, msg2); CRoutine::Yield(RoutineState::READY); } else { CRoutine::Yield(); } } }; }; return factory; } template <typename M0, typename M1, typename M2, typename M3, typename F> RoutineFactory CreateRoutineFactory( F&& f, const std::shared_ptr<data::DataVisitor<M0, M1, M2, M3>>& dv) { RoutineFactory factory; factory.SetDataVisitor(dv); factory.create_routine = [=]() { return [=]() { std::shared_ptr<M0> msg0; std::shared_ptr<M1> msg1; std::shared_ptr<M2> msg2; std::shared_ptr<M3> msg3; for (;;) { CRoutine::GetCurrentRoutine()->set_state(RoutineState::DATA_WAIT); if (dv->TryFetch(msg0, msg1, msg2, msg3)) { f(msg0, msg1, msg2, msg3); CRoutine::Yield(RoutineState::READY); } else { CRoutine::Yield(); } } }; }; return factory; } template <typename Function> RoutineFactory CreateRoutineFactory(Function&& f) { RoutineFactory factory; factory.create_routine = [f = std::forward<Function&&>(f)]() { return f; }; return factory; } } // namespace croutine } // namespace cyber } // namespace apollo #endif // CYBER_CROUTINE_ROUTINE_FACTORY_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/croutine/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_croutine_hdrs", srcs = glob([ "*.h", "detail/*.h" ]), ) cc_library( name = "croutine", srcs = ["croutine.cc"], hdrs = ["croutine.h"], linkopts = ["-latomic"], deps = [ "//cyber/base:atomic_hash_map", "//cyber/base:atomic_rw_lock", "//cyber/base:bounded_queue", "//cyber/base:concurrent_object_pool", "//cyber/base:macros", "//cyber/base:wait_strategy", "//cyber/common", "//cyber/croutine:routine_context", "//cyber/croutine:routine_factory", "//cyber/croutine:swap", "//cyber/event:perf_event_cache", "//cyber/time", ], ) cc_library( name = "routine_context", srcs = ["detail/routine_context.cc"], hdrs = ["detail/routine_context.h"], deps = [ "//cyber/common", ], ) cc_library( name = "routine_factory", hdrs = ["routine_factory.h"], deps = [ "//cyber/common", "//cyber/event:perf_event_cache", ], ) cc_library( name = "swap", srcs = select( { "@platforms//cpu:x86_64": [ "detail/swap_x86_64.S", ], "@platforms//cpu:aarch64": [ "detail/swap_aarch64.S", ], }, no_match_error = "Please Build with a Linux aarch64 or x86_64 platform", ), ) cc_test( name = "croutine_test", size = "small", srcs = ["croutine_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/croutine/croutine.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/croutine/croutine.h" #include <algorithm> #include <utility> #include "cyber/base/concurrent_object_pool.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/croutine/detail/routine_context.h" namespace apollo { namespace cyber { namespace croutine { thread_local CRoutine *CRoutine::current_routine_ = nullptr; thread_local char *CRoutine::main_stack_ = nullptr; namespace { std::shared_ptr<base::CCObjectPool<RoutineContext>> context_pool = nullptr; std::once_flag pool_init_flag; void CRoutineEntry(void *arg) { CRoutine *r = static_cast<CRoutine *>(arg); r->Run(); CRoutine::Yield(RoutineState::FINISHED); } } // namespace CRoutine::CRoutine(const std::function<void()> &func) : func_(func) { std::call_once(pool_init_flag, [&]() { uint32_t routine_num = common::GlobalData::Instance()->ComponentNums(); auto &global_conf = common::GlobalData::Instance()->Config(); if (global_conf.has_scheduler_conf() && global_conf.scheduler_conf().has_routine_num()) { routine_num = std::max(routine_num, global_conf.scheduler_conf().routine_num()); } context_pool.reset(new base::CCObjectPool<RoutineContext>(routine_num)); }); context_ = context_pool->GetObject(); if (context_ == nullptr) { AWARN << "Maximum routine context number exceeded! Please check " "[routine_num] in config file."; context_.reset(new RoutineContext()); } MakeContext(CRoutineEntry, this, context_.get()); state_ = RoutineState::READY; updated_.test_and_set(std::memory_order_release); } CRoutine::~CRoutine() { context_ = nullptr; } RoutineState CRoutine::Resume() { if (cyber_unlikely(force_stop_)) { state_ = RoutineState::FINISHED; return state_; } if (cyber_unlikely(state_ != RoutineState::READY)) { AERROR << "Invalid Routine State!"; return state_; } current_routine_ = this; SwapContext(GetMainStack(), GetStack()); current_routine_ = nullptr; return state_; } void CRoutine::Stop() { force_stop_ = true; } } // namespace croutine } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/croutine/croutine_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/croutine/croutine.h" #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/cyber.h" #include "cyber/init.h" namespace apollo { namespace cyber { namespace croutine { void function() { CRoutine::Yield(RoutineState::IO_WAIT); } TEST(Croutine, croutinetest) { apollo::cyber::Init("croutine_test"); std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(function); auto id = GlobalData::RegisterTaskName("croutine"); cr->set_id(id); cr->set_name("croutine"); cr->set_processor_id(0); cr->set_priority(1); cr->set_state(RoutineState::DATA_WAIT); EXPECT_EQ(cr->state(), RoutineState::DATA_WAIT); cr->Wake(); EXPECT_EQ(cr->state(), RoutineState::READY); cr->UpdateState(); EXPECT_EQ(cr->state(), RoutineState::READY); EXPECT_EQ(*(cr->GetMainStack()), nullptr); cr->Resume(); EXPECT_NE(*(cr->GetMainStack()), nullptr); EXPECT_EQ(cr->state(), RoutineState::IO_WAIT); cr->Stop(); EXPECT_EQ(cr->Resume(), RoutineState::FINISHED); } } // namespace croutine } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/croutine
apollo_public_repos/apollo/cyber/croutine/detail/routine_context.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/croutine/detail/routine_context.h" namespace apollo { namespace cyber { namespace croutine { // The stack layout looks as follows: // // +------------------+ // | Reserved | // +------------------+ // | Return Address | f1 // +------------------+ // | RDI | arg // +------------------+ // | R12 | // +------------------+ // | R13 | // +------------------+ // | ... | // +------------------+ // ctx->sp => | RBP | // +------------------+ void MakeContext(const func &f1, const void *arg, RoutineContext *ctx) { ctx->sp = ctx->stack + STACK_SIZE - 2 * sizeof(void *) - REGISTERS_SIZE; std::memset(ctx->sp, 0, REGISTERS_SIZE); #ifdef __aarch64__ char *sp = ctx->stack + STACK_SIZE - sizeof(void *); #else char *sp = ctx->stack + STACK_SIZE - 2 * sizeof(void *); #endif *reinterpret_cast<void **>(sp) = reinterpret_cast<void *>(f1); sp -= sizeof(void *); *reinterpret_cast<void **>(sp) = const_cast<void *>(arg); } } // namespace croutine } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/croutine
apollo_public_repos/apollo/cyber/croutine/detail/routine_context.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CROUTINE_ROUTINE_CONTEXT_H_ #define CYBER_CROUTINE_ROUTINE_CONTEXT_H_ #include <cstdlib> #include <cstring> #include <iostream> #include "cyber/common/log.h" extern "C" { extern void ctx_swap(void**, void**) asm("ctx_swap"); }; namespace apollo { namespace cyber { namespace croutine { constexpr size_t STACK_SIZE = 2 * 1024 * 1024; #if defined __aarch64__ constexpr size_t REGISTERS_SIZE = 160; #else constexpr size_t REGISTERS_SIZE = 56; #endif typedef void (*func)(void*); struct RoutineContext { char stack[STACK_SIZE]; char* sp = nullptr; #if defined __aarch64__ } __attribute__((aligned(16))); #else }; #endif void MakeContext(const func& f1, const void* arg, RoutineContext* ctx); inline void SwapContext(char** src_sp, char** dest_sp) { ctx_swap(reinterpret_cast<void**>(src_sp), reinterpret_cast<void**>(dest_sp)); } } // namespace croutine } // namespace cyber } // namespace apollo #endif // CYBER_CROUTINE_ROUTINE_CONTEXT_H_
0
apollo_public_repos/apollo/cyber/croutine
apollo_public_repos/apollo/cyber/croutine/detail/swap_x86_64.S
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ .globl ctx_swap .type ctx_swap, @function ctx_swap: pushq %rdi pushq %r12 pushq %r13 pushq %r14 pushq %r15 pushq %rbx pushq %rbp movq %rsp, (%rdi) movq (%rsi), %rsp popq %rbp popq %rbx popq %r15 popq %r14 popq %r13 popq %r12 popq %rdi ret
0
apollo_public_repos/apollo/cyber/croutine
apollo_public_repos/apollo/cyber/croutine/detail/swap_aarch64.S
.text .align 4 .globl ctx_swap ctx_swap: stp x0, x30, [sp,#-16]! stp d8, d9, [sp,#-16]! stp d10, d11, [sp,#-16]! stp d12, d13, [sp,#-16]! stp d14, d15, [sp,#-16]! stp x1, x19, [sp,#-16]! stp x20, x21, [sp,#-16]! stp x22, x23, [sp,#-16]! stp x24, x25, [sp,#-16]! stp x26, x27, [sp,#-16]! stp x28, x29, [sp,#-16]! mov x3, sp str x3, [x0] ldr x3, [x1] mov sp, x3 ldp x28, x29, [sp] ldp x26, x27, [sp,#16]! ldp x24, x25, [sp,#16]! ldp x22, x23, [sp,#16]! ldp x20, x21, [sp,#16]! ldp x1, x19, [sp,#16]! ldp d14, d15, [sp,#16]! ldp d12, d13, [sp,#16]! ldp d10, d11, [sp,#16]! ldp d8, d9, [sp,#16]! ldp x0, x30, [sp,#16]! add sp, sp, #16 ret
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/task/task.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_TASK_TASK_H_ #define CYBER_TASK_TASK_H_ #include <future> #include <utility> #include "cyber/task/task_manager.h" namespace apollo { namespace cyber { using apollo::cyber::common::GlobalData; template <typename F, typename... Args> static auto Async(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { return GlobalData::Instance()->IsRealityMode() ? TaskManager::Instance()->Enqueue(std::forward<F>(f), std::forward<Args>(args)...) : std::async( std::launch::async, std::bind(std::forward<F>(f), std::forward<Args>(args)...)); } static inline void Yield() { if (croutine::CRoutine::GetCurrentRoutine()) { croutine::CRoutine::Yield(); } else { std::this_thread::yield(); } } template <typename Rep, typename Period> static void SleepFor(const std::chrono::duration<Rep, Period>& sleep_duration) { auto routine = croutine::CRoutine::GetCurrentRoutine(); if (routine == nullptr) { std::this_thread::sleep_for(sleep_duration); } else { routine->Sleep(sleep_duration); } } static inline void USleep(useconds_t usec) { auto routine = croutine::CRoutine::GetCurrentRoutine(); if (routine == nullptr) { std::this_thread::sleep_for(std::chrono::microseconds{usec}); } else { routine->Sleep(croutine::Duration(usec)); } } } // namespace cyber } // namespace apollo #endif // CYBER_TASK_TASK_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/task/task_manager.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_TASK_TASK_MANAGER_H_ #define CYBER_TASK_TASK_MANAGER_H_ #include <atomic> #include <future> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include "cyber/base/bounded_queue.h" #include "cyber/scheduler/scheduler_factory.h" namespace apollo { namespace cyber { class TaskManager { public: virtual ~TaskManager(); void Shutdown(); template <typename F, typename... Args> auto Enqueue(F&& func, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>( std::bind(std::forward<F>(func), std::forward<Args>(args)...)); if (!stop_.load()) { task_queue_->Enqueue([task]() { (*task)(); }); for (auto& task : tasks_) { scheduler::Instance()->NotifyTask(task); } } std::future<return_type> res(task->get_future()); return res; } private: uint32_t num_threads_ = 0; uint32_t task_queue_size_ = 1000; std::atomic<bool> stop_ = {false}; std::vector<uint64_t> tasks_; std::shared_ptr<base::BoundedQueue<std::function<void()>>> task_queue_; DECLARE_SINGLETON(TaskManager); }; } // namespace cyber } // namespace apollo #endif // CYBER_TASK_TASK_MANAGER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/task/task_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/task/task.h" #include <memory> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/common/log.h" #include "cyber/cyber.h" #include "cyber/init.h" namespace apollo { namespace cyber { namespace scheduler { class Foo { public: void RunOnce() { auto res = Async(&Foo::Task, this, 10); EXPECT_EQ(res.get(), 10); } uint32_t Task(const uint32_t& input) { return input; } }; struct Message { uint64_t id; }; void Task1() { ADEBUG << "Task1 running"; } void Task2(const Message& input) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); ADEBUG << "Task2 running"; } uint64_t Task3(const std::shared_ptr<Message>& input) { ADEBUG << "Task3 running"; return input->id; } TEST(AsyncTest, create_task) { auto task_1 = Async(&Task1); task_1.get(); Message msg; auto task_2 = Async(&Task2, msg); task_2.get(); auto shared_msg = std::make_shared<Message>(); shared_msg->id = 1; auto task_3 = Async(&Task3, shared_msg); EXPECT_EQ(task_3.get(), 1); } TEST(AsyncTest, batch_run) { std::vector<std::future<void>> void_results; for (int i = 0; i < 10; i++) { void_results.push_back(Async(&Task1)); } for (auto& result : void_results) { result.get(); } int loop = 10; std::vector<std::future<uint64_t>> int_results; for (int i = 0; i < loop; i++) { auto shared_msg = std::make_shared<Message>(); shared_msg->id = i; int_results.push_back(Async(&Task3, shared_msg)); } for (int i = 0; i < loop; i++) { EXPECT_EQ(int_results[i].get(), i); } } TEST(AsyncTest, run_member_function) { Foo foo; foo.RunOnce(); } } // namespace scheduler } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/task/task_manager.cc
/**************Scheduler::**************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Vesched_infoon 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. *****************************************************************************/ #include "cyber/task/task_manager.h" #include "cyber/common/global_data.h" #include "cyber/croutine/croutine.h" #include "cyber/croutine/routine_factory.h" #include "cyber/scheduler/scheduler_factory.h" namespace apollo { namespace cyber { using apollo::cyber::common::GlobalData; static const char* const task_prefix = "/internal/task"; TaskManager::TaskManager() : task_queue_size_(1000), task_queue_(new base::BoundedQueue<std::function<void()>>()) { if (!task_queue_->Init(task_queue_size_, new base::BlockWaitStrategy())) { AERROR << "Task queue init failed"; throw std::runtime_error("Task queue init failed"); } auto func = [this]() { while (!stop_) { std::function<void()> task; if (!task_queue_->Dequeue(&task)) { auto routine = croutine::CRoutine::GetCurrentRoutine(); routine->HangUp(); continue; } task(); } }; num_threads_ = scheduler::Instance()->TaskPoolSize(); auto factory = croutine::CreateRoutineFactory(std::move(func)); tasks_.reserve(num_threads_); for (uint32_t i = 0; i < num_threads_; i++) { auto task_name = task_prefix + std::to_string(i); tasks_.push_back(common::GlobalData::RegisterTaskName(task_name)); if (!scheduler::Instance()->CreateTask(factory, task_name)) { AERROR << "CreateTask failed:" << task_name; } } } TaskManager::~TaskManager() { Shutdown(); } void TaskManager::Shutdown() { if (stop_.exchange(true)) { return; } for (uint32_t i = 0; i < num_threads_; i++) { scheduler::Instance()->RemoveTask(task_prefix + std::to_string(i)); } } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/task/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_task_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "task", hdrs = ["task.h"], deps = [ ":task_manager", ], ) cc_test( name = "task_test", size = "small", srcs = ["task_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "task_manager", srcs = ["task_manager.cc"], hdrs = ["task_manager.h"], copts = ["-faligned-new"], deps = [ "//cyber/scheduler:scheduler_factory", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter.h" #include "cyber/message/protobuf_factory.h" namespace apollo { namespace cyber { using apollo::cyber::message::ProtobufFactory; Parameter::Parameter() { param_.set_name(""); param_.set_type(ParamType::NOT_SET); } Parameter::Parameter(const std::string& name) { param_.set_name(name); param_.set_type(proto::ParamType::NOT_SET); } Parameter::Parameter(const Parameter& parameter) { param_.CopyFrom(parameter.param_); } Parameter::Parameter(const std::string& name, const bool bool_value) { param_.set_name(name); param_.set_bool_value(bool_value); param_.set_type(ParamType::BOOL); param_.set_type_name("BOOL"); } Parameter::Parameter(const std::string& name, const int int_value) { param_.set_name(name); param_.set_int_value(int_value); param_.set_type(ParamType::INT); param_.set_type_name("INT"); } Parameter::Parameter(const std::string& name, const int64_t int_value) { param_.set_name(name); param_.set_int_value(int_value); param_.set_type(ParamType::INT); param_.set_type_name("INT"); } Parameter::Parameter(const std::string& name, const float double_value) { param_.set_name(name); param_.set_double_value(double_value); param_.set_type(ParamType::DOUBLE); param_.set_type_name("DOUBLE"); } Parameter::Parameter(const std::string& name, const double double_value) { param_.set_name(name); param_.set_double_value(double_value); param_.set_type(ParamType::DOUBLE); param_.set_type_name("DOUBLE"); } Parameter::Parameter(const std::string& name, const std::string& string_value) { param_.set_name(name); param_.set_string_value(string_value); param_.set_type(ParamType::STRING); param_.set_type_name("STRING"); } Parameter::Parameter(const std::string& name, const char* string_value) { param_.set_name(name); param_.set_string_value(string_value); param_.set_type(ParamType::STRING); param_.set_type_name("STRING"); } Parameter::Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc) { param_.set_name(name); param_.set_string_value(msg_str); param_.set_type(ParamType::PROTOBUF); param_.set_type_name(full_name); param_.set_proto_desc(proto_desc); } Parameter::Parameter(const std::string& name, const google::protobuf::Message& msg) { param_.set_name(name); std::string str; msg.SerializeToString(&str); std::string desc; ProtobufFactory::GetDescriptorString(msg, &desc); param_.set_string_value(str); param_.set_type(ParamType::PROTOBUF); param_.set_type_name(msg.GetDescriptor()->full_name()); param_.set_proto_desc(desc); } void Parameter::FromProtoParam(const Param& param) { param_.CopyFrom(param); } Param Parameter::ToProtoParam() const { return param_; } std::string Parameter::DebugString() const { std::stringstream ss; ss << "{name: \"" << param_.name() << "\", "; ss << "type: \"" << TypeName() << "\", "; ss << "value: "; switch (Type()) { case ParamType::BOOL: { ss << (AsBool() ? "true" : "false"); break; } case ParamType::INT: { ss << std::to_string(AsInt64()); break; } case ParamType::DOUBLE: { ss << std::to_string(AsDouble()); break; } case ParamType::STRING: { ss << "\"" << AsString() << "\""; break; } case ParamType::PROTOBUF: { ProtobufFactory::Instance()->RegisterMessage(Descriptor()); auto message = ProtobufFactory::Instance()->GenerateMessageByType(TypeName()); if (message != nullptr) { message->ParseFromString(AsString()); ss << "\"" << message->ShortDebugString() << "\""; delete message; } break; } case ParamType::NOT_SET: { ss << "not set"; break; } default: // do nothing break; } ss << "}"; return ss.str(); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_client_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter_client.h" #include <memory> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/message/protobuf_factory.h" #include "cyber/parameter/parameter_server.h" namespace apollo { namespace cyber { class ParameterClientTest : public ::testing::Test { protected: ParameterClientTest() { apollo::cyber::Init("parameter_client_test"); SetState(STATE_INITIALIZED); node_ = CreateNode("parameter_server"); } virtual void SetUp() { // Called before every TEST_F(ParameterClientTest, *) ps_.reset(new ParameterServer(node_)); pc_.reset(new ParameterClient(node_, "parameter_server")); } virtual void TearDown() { // Called after every TEST_F(ParameterClientTest, *) ps_.reset(); pc_.reset(); } protected: std::shared_ptr<Node> node_; std::unique_ptr<ParameterServer> ps_; std::unique_ptr<ParameterClient> pc_; }; TEST_F(ParameterClientTest, set_parameter) { EXPECT_TRUE(pc_->SetParameter(Parameter("int", 1))); std::this_thread::sleep_for(std::chrono::milliseconds(100)); ps_.reset(); EXPECT_FALSE(pc_->SetParameter(Parameter("int", 1))); } TEST_F(ParameterClientTest, get_parameter) { ps_->SetParameter(Parameter("int", 1)); Parameter parameter; EXPECT_TRUE(pc_->GetParameter("int", &parameter)); EXPECT_EQ("int", parameter.Name()); EXPECT_EQ(1, parameter.AsInt64()); EXPECT_FALSE(pc_->GetParameter("double", &parameter)); ps_.reset(); EXPECT_FALSE(pc_->GetParameter("int", &parameter)); } TEST_F(ParameterClientTest, list_parameter) { ps_->SetParameter(Parameter("int", 1)); std::vector<Parameter> parameters; EXPECT_TRUE(pc_->ListParameters(&parameters)); EXPECT_EQ(1, parameters.size()); EXPECT_EQ("int", parameters[0].Name()); EXPECT_EQ(1, parameters[0].AsInt64()); ps_.reset(); EXPECT_FALSE(pc_->ListParameters(&parameters)); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_client.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_PARAMETER_PARAMETER_CLIENT_H_ #define CYBER_PARAMETER_PARAMETER_CLIENT_H_ #include <memory> #include <string> #include <vector> #include "cyber/proto/parameter.pb.h" #include "cyber/parameter/parameter.h" #include "cyber/service/client.h" namespace apollo { namespace cyber { class Node; /** * @class ParameterClient * @brief Parameter Client is used to set/get/list parameter(s) * by sending a request to ParameterServer */ class ParameterClient { public: using Param = apollo::cyber::proto::Param; using NodeName = apollo::cyber::proto::NodeName; using ParamName = apollo::cyber::proto::ParamName; using BoolResult = apollo::cyber::proto::BoolResult; using Params = apollo::cyber::proto::Params; using GetParameterClient = Client<ParamName, Param>; using SetParameterClient = Client<Param, BoolResult>; using ListParametersClient = Client<NodeName, Params>; /** * @brief Construct a new ParameterClient object * * @param node shared_ptr of the node handler * @param service_node_name node name which provide a param services */ ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name); /** * @brief Get the Parameter object * * @param param_name * @param parameter the pointer to store * @return true * @return false call service fail or timeout */ bool GetParameter(const std::string& param_name, Parameter* parameter); /** * @brief Set the Parameter object * * @param parameter parameter to be set * @return true set parameter succues * @return false 1. call service timeout * 2. parameter not exists * The corresponding log will be recorded at the same time */ bool SetParameter(const Parameter& parameter); /** * @brief Get all the Parameter objects * * @param parameters pointer of vector to store all the parameters * @return true * @return false call service fail or timeout */ bool ListParameters(std::vector<Parameter>* parameters); private: std::shared_ptr<Node> node_; std::shared_ptr<GetParameterClient> get_parameter_client_; std::shared_ptr<SetParameterClient> set_parameter_client_; std::shared_ptr<ListParametersClient> list_parameters_client_; }; } // namespace cyber } // namespace apollo #endif // CYBER_PARAMETER_PARAMETER_CLIENT_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_server_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter_server.h" #include <memory> #include <vector> #include "gtest/gtest.h" #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/message/protobuf_factory.h" namespace apollo { namespace cyber { class ParameterServerTest : public ::testing::Test { protected: ParameterServerTest() { apollo::cyber::Init("parameter_server_test"); node_ = CreateNode("parameter_server"); } virtual void SetUp() { // Called before every TEST_F(ParameterServerTest, *) ps_.reset(new ParameterServer(node_)); } virtual void TearDown() { ps_.reset(); } protected: std::shared_ptr<Node> node_; std::unique_ptr<ParameterServer> ps_; }; TEST_F(ParameterServerTest, set_parameter) { ps_->SetParameter(Parameter("int", 1)); } TEST_F(ParameterServerTest, get_parameter) { ps_->SetParameter(Parameter("int", 1)); Parameter parameter; ps_->GetParameter("int", &parameter); EXPECT_EQ("int", parameter.Name()); EXPECT_EQ(1, parameter.AsInt64()); } TEST_F(ParameterServerTest, list_parameter) { ps_->SetParameter(Parameter("int", 1)); std::vector<Parameter> parameters; ps_->ListParameters(&parameters); EXPECT_EQ(1, parameters.size()); EXPECT_EQ("int", parameters[0].Name()); EXPECT_EQ(1, parameters[0].AsInt64()); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_server.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter_server.h" #include "cyber/common/log.h" #include "cyber/node/node.h" #include "cyber/parameter/parameter_service_names.h" namespace apollo { namespace cyber { ParameterServer::ParameterServer(const std::shared_ptr<Node>& node) : node_(node) { auto name = node_->Name(); get_parameter_service_ = node_->CreateService<ParamName, Param>( FixParameterServiceName(name, GET_PARAMETER_SERVICE_NAME), [this](const std::shared_ptr<ParamName>& request, std::shared_ptr<Param>& response) { std::lock_guard<std::mutex> lock(param_map_mutex_); if (param_map_.find(request->value()) != param_map_.end()) { response->CopyFrom(param_map_[request->value()]); } else { AINFO << "GetParameterService: [" << request->value() << "] not set"; } }); set_parameter_service_ = node_->CreateService<Param, BoolResult>( FixParameterServiceName(name, SET_PARAMETER_SERVICE_NAME), [this](const std::shared_ptr<Param>& request, std::shared_ptr<BoolResult>& response) { std::lock_guard<std::mutex> lock(param_map_mutex_); param_map_[request->name()] = *request; response->set_value(true); }); list_parameters_service_ = node_->CreateService<NodeName, Params>( FixParameterServiceName(name, LIST_PARAMETERS_SERVICE_NAME), [this](const std::shared_ptr<NodeName>& request, std::shared_ptr<Params>& response) { std::lock_guard<std::mutex> lock(param_map_mutex_); for (auto& item : param_map_) { auto param = response->add_param(); param->CopyFrom(item.second); } }); } void ParameterServer::SetParameter(const Parameter& parameter) { std::lock_guard<std::mutex> lock(param_map_mutex_); param_map_[parameter.Name()] = parameter.ToProtoParam(); } bool ParameterServer::GetParameter(const std::string& parameter_name, Parameter* parameter) { std::lock_guard<std::mutex> lock(param_map_mutex_); auto ite = param_map_.find(parameter_name); if (ite == param_map_.end()) { return false; } parameter->FromProtoParam(ite->second); return true; } void ParameterServer::ListParameters(std::vector<Parameter>* parameters) { std::lock_guard<std::mutex> lock(param_map_mutex_); for (auto& item : param_map_) { Parameter parameter; parameter.FromProtoParam(item.second); parameters->emplace_back(parameter); } } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_PARAMETER_PARAMETER_H_ #define CYBER_PARAMETER_PARAMETER_H_ #include <string> #include "cyber/proto/parameter.pb.h" #include "cyber/common/log.h" /** * @namespace cyber.parameter */ namespace apollo { namespace cyber { using apollo::cyber::proto::Param; using apollo::cyber::proto::ParamType; /** * @class Parameter * @brief A `Parameter` holds an apollo::cyber::proto::Param, * It's more human-readable, you can use basic-value type and Protobuf values * to construct a paramter. Parameter is identified by their `name`, * and you can get Parameter content by call value() */ class Parameter { public: /** * @brief Empty constructor */ Parameter(); /** * @brief copy constructor */ explicit Parameter(const Parameter& parameter); /** * @brief construct with paramter's name * * @param name Parameter name */ explicit Parameter(const std::string& name); /** * @brief construct with paramter's name and bool value type * * @param name Parameter name * @param bool_value bool value */ Parameter(const std::string& name, const bool bool_value); /** * @brief construct with paramter's name and int value type * * @param name Parameter name * @param int_value int value */ Parameter(const std::string& name, const int int_value); /** * @brief construct with paramter's name and int value type * * @param name Parameter name * @param int_value int value */ Parameter(const std::string& name, const int64_t int_value); /** * @brief construct with paramter's name and float value type * * @param name Parameter name * @param float_value float value */ Parameter(const std::string& name, const float float_value); /** * @brief construct with paramter's name and double value type * * @param name Parameter name * @param double_value double value */ Parameter(const std::string& name, const double double_value); /** * @brief construct with paramter's name and string value type * * @param name Parameter name * @param string_value string value */ Parameter(const std::string& name, const std::string& string_value); /** * @brief construct with paramter's name and char* value type * * @param name Parameter name * @param string_value char* value */ Parameter(const std::string& name, const char* string_value); /** * @brief use a protobuf type value to construct the parameter * * @param name Parameter name * @param msg_str protobuf contents * @param full_name the proto full name * @param proto_desc the proto's description */ Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc); /** * @brief use a google::protobuf::Message type value to construct the * parameter * * @param name Parameter name * @param msg protobuf message */ Parameter(const std::string& name, const google::protobuf::Message& msg); /** * @brief Parse a cyber::proto::Param object to * cyber::parameter::Parameter object * @param param The cyber::proto::Param object parse from * A pointer to the target Parameter object * @return True if parse ok, otherwise False */ void FromProtoParam(const Param& param); /** * @brief Parse a cyber::parameter::Parameter object to * cyber::proto::Param object * @return The target cyber::proto::Param object */ Param ToProtoParam() const; /** * @brief Get the cyber:parameter::ParamType of this object * @return result cyber:parameter::ParameterType */ inline ParamType Type() const; /** * @brief Get Paramter's type name, i.e. * INT,DOUBLE,STRING or protobuf message's fullname * * @return std::string the Parameter's type name */ inline std::string TypeName() const; /** * @brief Get Paramter's descriptor, only work on protobuf types * * @return std::string the Parameter's type name */ inline std::string Descriptor() const; /** * @brief Get the Parameter name * * @return const std::string the Parameter's name */ inline const std::string Name() const; /** * @brief Get Paramter as a bool value * * @return true result * @return false result */ inline bool AsBool() const; /** * @brief Get Paramter as an int64_t value * * @return int64_t int64 type result */ inline int64_t AsInt64() const; /** * @brief et Paramter as a double value * * @return double type result */ inline double AsDouble() const; /** * @brief Get Paramter as a string value * * @return const std::string Parameter's string expression */ inline const std::string AsString() const; /** * @brief show debug string * * @return std::string Parameter's debug string */ std::string DebugString() const; /** * @brief Translate paramter value as a protobuf::Message * * @tparam ValueType type of the value * @return std::enable_if< std::is_base_of<google::protobuf::Message, ValueType>::value, ValueType>::type protobuf::Message type result */ template <typename ValueType> typename std::enable_if< std::is_base_of<google::protobuf::Message, ValueType>::value, ValueType>::type value() const; /** * @brief Translate paramter value to int type * * @tparam ValueType type of the value * @return std::enable_if<std::is_integral<ValueType>::value && !std::is_same<ValueType, bool>::value, ValueType>::type int type result */ template <typename ValueType> typename std::enable_if<std::is_integral<ValueType>::value && !std::is_same<ValueType, bool>::value, ValueType>::type value() const; /** * @brief Translate paramter value to bool type * * @tparam ValueType type of the value * @return std::enable_if<std::is_floating_point<ValueType>::value, ValueType>::type floating type result */ template <typename ValueType> typename std::enable_if<std::is_floating_point<ValueType>::value, ValueType>::type value() const; /** * @brief Translate paramter value to string type * * @tparam ValueType type of the value * @return std::enable_if<std::is_convertible<ValueType, std::string>::value, const std::string&>::type string type result */ template <typename ValueType> typename std::enable_if<std::is_convertible<ValueType, std::string>::value, const std::string&>::type value() const; /** * @brief Translate paramter value to bool type * * @tparam ValueType type of the value * @return std::enable_if<std::is_same<ValueType, bool>::value, bool>::type * bool type result */ template <typename ValueType> typename std::enable_if<std::is_same<ValueType, bool>::value, bool>::type value() const; private: Param param_; }; template <typename ValueType> typename std::enable_if< std::is_base_of<google::protobuf::Message, ValueType>::value, ValueType>::type Parameter::value() const { ValueType message; if (!message.ParseFromString(param_.string_value())) { AERROR << "The type of parameter \"" << param_.name() << "\" is " << TypeName() << ", not " << ValueType::descriptor()->full_name(); } return message; } template <typename ValueType> typename std::enable_if<std::is_integral<ValueType>::value && !std::is_same<ValueType, bool>::value, ValueType>::type Parameter::value() const { if (param_.type() != proto::ParamType::INT) { AERROR << "The type of parameter \"" << param_.name() << "\" is " << TypeName() << ", not INT"; } return static_cast<ValueType>(param_.int_value()); } template <typename ValueType> typename std::enable_if<std::is_floating_point<ValueType>::value, ValueType>::type Parameter::value() const { if (param_.type() != proto::ParamType::DOUBLE) { AERROR << "The type of parameter \"" << param_.name() << "\" is " << TypeName() << ", not DOUBLE"; } return static_cast<ValueType>(param_.double_value()); } template <typename ValueType> typename std::enable_if<std::is_convertible<ValueType, std::string>::value, const std::string&>::type Parameter::value() const { if (param_.type() != proto::ParamType::STRING && param_.type() != proto::ParamType::PROTOBUF) { AERROR << "The type of parameter \"" << param_.name() << "\" is " << TypeName() << ", not STRING"; } return param_.string_value(); } template <typename ValueType> typename std::enable_if<std::is_same<ValueType, bool>::value, bool>::type Parameter::value() const { if (param_.type() != proto::ParamType::BOOL) { AERROR << "The type of parameter \"" << param_.name() << "\" is " << TypeName() << ", not BOOL"; } return param_.bool_value(); } inline ParamType Parameter::Type() const { return param_.type(); } inline std::string Parameter::TypeName() const { return param_.type_name(); } inline std::string Parameter::Descriptor() const { return param_.proto_desc(); } inline const std::string Parameter::Name() const { return param_.name(); } inline bool Parameter::AsBool() const { return value<bool>(); } inline int64_t Parameter::AsInt64() const { return value<int64_t>(); } inline double Parameter::AsDouble() const { return value<double>(); } const std::string Parameter::AsString() const { return value<std::string>(); } } // namespace cyber } // namespace apollo #endif // CYBER_PARAMETER_PARAMETER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_client.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter_client.h" #include "cyber/node/node.h" #include "cyber/parameter/parameter_service_names.h" namespace apollo { namespace cyber { ParameterClient::ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name) : node_(node) { get_parameter_client_ = node_->CreateClient<ParamName, Param>( FixParameterServiceName(service_node_name, GET_PARAMETER_SERVICE_NAME)); set_parameter_client_ = node_->CreateClient<Param, BoolResult>( FixParameterServiceName(service_node_name, SET_PARAMETER_SERVICE_NAME)); list_parameters_client_ = node_->CreateClient<NodeName, Params>( FixParameterServiceName(service_node_name, LIST_PARAMETERS_SERVICE_NAME)); } bool ParameterClient::GetParameter(const std::string& param_name, Parameter* parameter) { auto request = std::make_shared<ParamName>(); request->set_value(param_name); auto response = get_parameter_client_->SendRequest(request); if (response == nullptr) { AERROR << "Call " << get_parameter_client_->ServiceName() << " failed"; return false; } if (response->type() == ParamType::NOT_SET) { AWARN << "Parameter " << param_name << " not exists yet."; return false; } parameter->FromProtoParam(*response); return true; } bool ParameterClient::SetParameter(const Parameter& parameter) { auto request = std::make_shared<Param>(parameter.ToProtoParam()); auto response = set_parameter_client_->SendRequest(request); if (response == nullptr) { AERROR << "Call " << set_parameter_client_->ServiceName() << " failed"; return false; } return response->value(); } bool ParameterClient::ListParameters(std::vector<Parameter>* parameters) { auto request = std::make_shared<NodeName>(); request->set_value(node_->Name()); auto response = list_parameters_client_->SendRequest(request); if (response == nullptr) { AERROR << "Call " << list_parameters_client_->ServiceName() << " failed"; return false; } for (auto& param : response->param()) { Parameter parameter; parameter.FromProtoParam(param); parameters->emplace_back(parameter); } return true; } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/parameter/parameter.h" #include <string> #include "gtest/gtest.h" #include "cyber/proto/parameter.pb.h" #include "cyber/cyber.h" #include "cyber/message/message_traits.h" namespace apollo { namespace cyber { using apollo::cyber::proto::Param; using apollo::cyber::proto::ParamType; class ParameterTest : public ::testing::Test { protected: virtual void SetUp() { // Called before every TEST_F(ParameterTest, *) bool_param_.reset(new Parameter("bool", true)); int_param_.reset(new Parameter("int", 100)); double_param_.reset(new Parameter("double", 0.0f)); string_param_.reset(new Parameter("string", "test")); proto::Param param; param.set_name("param"); std::string str; param.SerializeToString(&str); std::string desc; message::GetDescriptorString(param, &desc); std::string full_name = proto::Param::descriptor()->full_name(); protobuf_param_.reset(new Parameter("protobuf", str, full_name, desc)); } virtual void TearDown() { bool_param_.reset(); int_param_.reset(); double_param_.reset(); string_param_.reset(); protobuf_param_.reset(); } protected: std::unique_ptr<Parameter> bool_param_; std::unique_ptr<Parameter> int_param_; std::unique_ptr<Parameter> double_param_; std::unique_ptr<Parameter> string_param_; std::unique_ptr<Parameter> protobuf_param_; }; TEST_F(ParameterTest, constructors) { Parameter param("test"); EXPECT_EQ(ParamType::NOT_SET, param.Type()); Parameter param2(param); EXPECT_EQ(ParamType::NOT_SET, param2.Type()); } TEST_F(ParameterTest, from_pb) { proto::Param param; param.set_name("test"); param.set_type(proto::ParamType::INT); param.set_int_value(100); Parameter pv; pv.FromProtoParam(param); EXPECT_EQ("test", pv.Name()); EXPECT_EQ(ParamType::INT, pv.Type()); EXPECT_EQ(100, pv.AsInt64()); param.set_name("test_bool"); param.set_type(proto::ParamType::BOOL); param.set_bool_value(true); pv.FromProtoParam(param); EXPECT_TRUE(pv.AsBool()); param.set_name("test_double"); param.set_type(proto::ParamType::DOUBLE); param.set_double_value(10.00); pv.FromProtoParam(param); EXPECT_EQ(ParamType::DOUBLE, pv.Type()); param.set_name("test_string"); param.set_type(proto::ParamType::STRING); param.set_string_value("xxxxxx"); pv.FromProtoParam(param); EXPECT_EQ("xxxxxx", pv.AsString()); } TEST_F(ParameterTest, to_pb) { proto::Param param = int_param_->ToProtoParam(); EXPECT_EQ("int", param.name()); EXPECT_EQ(ParamType::INT, param.type()); EXPECT_EQ(100, param.int_value()); } TEST_F(ParameterTest, type) { EXPECT_EQ(ParamType::BOOL, bool_param_->Type()); EXPECT_EQ(ParamType::INT, int_param_->Type()); EXPECT_EQ(ParamType::DOUBLE, double_param_->Type()); EXPECT_EQ(ParamType::STRING, string_param_->Type()); EXPECT_EQ(ParamType::PROTOBUF, protobuf_param_->Type()); } TEST_F(ParameterTest, type_name) { EXPECT_EQ("BOOL", bool_param_->TypeName()); EXPECT_EQ("INT", int_param_->TypeName()); EXPECT_EQ("DOUBLE", double_param_->TypeName()); EXPECT_EQ("STRING", string_param_->TypeName()); EXPECT_EQ("apollo.cyber.proto.Param", protobuf_param_->TypeName()); } TEST_F(ParameterTest, name) { EXPECT_EQ("bool", bool_param_->Name()); EXPECT_EQ("int", int_param_->Name()); EXPECT_EQ("double", double_param_->Name()); EXPECT_EQ("string", string_param_->Name()); EXPECT_EQ("protobuf", protobuf_param_->Name()); } TEST_F(ParameterTest, as_bool) { EXPECT_TRUE(bool_param_->AsBool()); EXPECT_FALSE(Parameter("bool", false).AsBool()); } TEST_F(ParameterTest, as_int) { EXPECT_EQ(100, int_param_->AsInt64()); } TEST_F(ParameterTest, as_double) { EXPECT_EQ(0.0, double_param_->AsDouble()); } TEST_F(ParameterTest, AsString) { EXPECT_EQ(string_param_->AsString(), "test"); } TEST_F(ParameterTest, value) { EXPECT_TRUE(bool_param_->value<bool>()); EXPECT_EQ("", bool_param_->value<std::string>()); EXPECT_EQ(100, int_param_->value<uint8_t>()); EXPECT_EQ(100, int_param_->value<uint32_t>()); EXPECT_EQ(100, int_param_->value<int64_t>()); EXPECT_EQ(100, int_param_->value<int>()); EXPECT_EQ("", int_param_->value<std::string>()); EXPECT_EQ(0.0, double_param_->value<float>()); EXPECT_EQ(0.0, double_param_->value<double>()); EXPECT_EQ("", double_param_->value<std::string>()); EXPECT_EQ("test", string_param_->value<std::string>()); string_param_->value<int>(); auto param = protobuf_param_->value<proto::Param>(); EXPECT_EQ("protobuf", protobuf_param_->Name()); EXPECT_EQ("apollo.cyber.proto.Param", protobuf_param_->TypeName()); std::string str; param.SerializeToString(&str); EXPECT_EQ(str, protobuf_param_->value<std::string>()); protobuf_param_->value<int>(); } TEST_F(ParameterTest, debug_string) { EXPECT_EQ("{name: \"bool\", type: \"BOOL\", value: true}", bool_param_->DebugString()); EXPECT_EQ("{name: \"int\", type: \"INT\", value: 100}", int_param_->DebugString()); EXPECT_EQ("{name: \"double\", type: \"DOUBLE\", value: 0.000000}", double_param_->DebugString()); EXPECT_EQ("{name: \"string\", type: \"STRING\", value: \"test\"}", string_param_->DebugString()); EXPECT_EQ( "{name: \"protobuf\", type: \"apollo.cyber.proto.Param\", value: " "\"name: \"param\"\"}", protobuf_param_->DebugString()); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_service_names.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_PARAMETER_PARAMETER_SERVICE_NAMES_H_ #define CYBER_PARAMETER_PARAMETER_SERVICE_NAMES_H_ #include <string> namespace apollo { namespace cyber { constexpr auto SERVICE_NAME_DELIMITER = "/"; constexpr auto GET_PARAMETER_SERVICE_NAME = "get_parameter"; constexpr auto SET_PARAMETER_SERVICE_NAME = "set_parameter"; constexpr auto LIST_PARAMETERS_SERVICE_NAME = "list_parameters"; static inline std::string FixParameterServiceName(const std::string& node_name, const char* service_name) { return node_name + std::string(SERVICE_NAME_DELIMITER) + std::string(service_name); } } // namespace cyber } // namespace apollo #endif // CYBER_PARAMETER_PARAMETER_SERVICE_NAMES_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_parameter_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "parameter", srcs = ["parameter.cc"], hdrs = ["parameter.h"], deps = [ "//cyber/message:protobuf_factory", "//cyber/proto:parameter_cc_proto", ], alwayslink = True, ) cc_test( name = "parameter_test", size = "small", srcs = ["parameter_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "parameter_client", srcs = ["parameter_client.cc"], hdrs = ["parameter_client.h"], deps = [ ":parameter", ":parameter_service_names", "//cyber/node", "//cyber/service:client", "@fastrtps", ], alwayslink = True, ) cc_test( name = "parameter_client_test", size = "small", srcs = ["parameter_client_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "parameter_server", srcs = ["parameter_server.cc"], hdrs = ["parameter_server.h"], deps = [ ":parameter", ":parameter_service_names", "//cyber/node", "//cyber/service", "@fastrtps", ], alwayslink = True, ) cc_test( name = "parameter_server_test", size = "small", srcs = ["parameter_server_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "parameter_service_names", hdrs = ["parameter_service_names.h"], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/parameter/parameter_server.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_PARAMETER_PARAMETER_SERVER_H_ #define CYBER_PARAMETER_PARAMETER_SERVER_H_ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "cyber/proto/parameter.pb.h" #include "cyber/parameter/parameter.h" #include "cyber/service/service.h" namespace apollo { namespace cyber { class Node; /** * @class ParameterServer * @brief Parameter Service is a very important function of auto-driving. * If you want to set a key-value, and hope other nodes to get the value, * Routing, sensor internal/external references are set by Parameter Service * ParameterServer can set a parameter, and then you can get/list * paramter(s) by start a ParameterClient to send responding request * @warning You should only have one ParameterServer works */ class ParameterServer { public: using Param = apollo::cyber::proto::Param; using NodeName = apollo::cyber::proto::NodeName; using ParamName = apollo::cyber::proto::ParamName; using BoolResult = apollo::cyber::proto::BoolResult; using Params = apollo::cyber::proto::Params; /** * @brief Construct a new ParameterServer object * * @param node shared_ptr of the node handler */ explicit ParameterServer(const std::shared_ptr<Node>& node); /** * @brief Set the Parameter object * * @param parmeter parameter to be set */ void SetParameter(const Parameter& parmeter); /** * @brief Get the Parameter object * * @param parameter_name name of the parameer want to get * @param parameter pointer to store parameter want to get * @return true get parameter success * @return false parameter not exists */ bool GetParameter(const std::string& parameter_name, Parameter* parameter); /** * @brief get all the parameters * * @param parameters result Paramter vector */ void ListParameters(std::vector<Parameter>* parameters); private: std::shared_ptr<Node> node_; std::shared_ptr<Service<ParamName, Param>> get_parameter_service_; std::shared_ptr<Service<Param, BoolResult>> set_parameter_service_; std::shared_ptr<Service<NodeName, Params>> list_parameters_service_; std::mutex param_map_mutex_; std::unordered_map<std::string, Param> param_map_; }; } // namespace cyber } // namespace apollo #endif // CYBER_PARAMETER_PARAMETER_SERVER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_CLASS_LOADER_H_ #define CYBER_CLASS_LOADER_CLASS_LOADER_H_ #include <algorithm> #include <functional> #include <memory> #include <mutex> #include <string> #include <vector> #include "cyber/class_loader/class_loader_register_macro.h" namespace apollo { namespace cyber { namespace class_loader { /** * for library load,createclass object */ class ClassLoader { public: explicit ClassLoader(const std::string& library_path); virtual ~ClassLoader(); bool IsLibraryLoaded(); bool LoadLibrary(); int UnloadLibrary(); const std::string GetLibraryPath() const; template <typename Base> std::vector<std::string> GetValidClassNames(); template <typename Base> std::shared_ptr<Base> CreateClassObj(const std::string& class_name); template <typename Base> bool IsClassValid(const std::string& class_name); private: template <typename Base> void OnClassObjDeleter(Base* obj); private: std::string library_path_; int loadlib_ref_count_; std::mutex loadlib_ref_count_mutex_; int classobj_ref_count_; std::mutex classobj_ref_count_mutex_; }; template <typename Base> std::vector<std::string> ClassLoader::GetValidClassNames() { return (utility::GetValidClassNames<Base>(this)); } template <typename Base> bool ClassLoader::IsClassValid(const std::string& class_name) { std::vector<std::string> valid_classes = GetValidClassNames<Base>(); return (std::find(valid_classes.begin(), valid_classes.end(), class_name) != valid_classes.end()); } template <typename Base> std::shared_ptr<Base> ClassLoader::CreateClassObj( const std::string& class_name) { if (!IsLibraryLoaded()) { LoadLibrary(); } Base* class_object = utility::CreateClassObj<Base>(class_name, this); if (class_object == nullptr) { AWARN << "CreateClassObj failed, ensure class has been registered. " << "classname: " << class_name << ",lib: " << GetLibraryPath(); return std::shared_ptr<Base>(); } std::lock_guard<std::mutex> lck(classobj_ref_count_mutex_); classobj_ref_count_ = classobj_ref_count_ + 1; std::shared_ptr<Base> classObjSharePtr( class_object, std::bind(&ClassLoader::OnClassObjDeleter<Base>, this, std::placeholders::_1)); return classObjSharePtr; } template <typename Base> void ClassLoader::OnClassObjDeleter(Base* obj) { if (nullptr == obj) { return; } std::lock_guard<std::mutex> lck(classobj_ref_count_mutex_); delete obj; --classobj_ref_count_; } } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_CLASS_LOADER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader_register_macro.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_CLASS_LOADER_REGISTER_MACRO_H_ #define CYBER_CLASS_LOADER_CLASS_LOADER_REGISTER_MACRO_H_ #include "cyber/class_loader/utility/class_loader_utility.h" #define CLASS_LOADER_REGISTER_CLASS_INTERNAL(Derived, Base, UniqueID) \ namespace { \ struct ProxyType##UniqueID { \ ProxyType##UniqueID() { \ apollo::cyber::class_loader::utility::RegisterClass<Derived, Base>( \ #Derived, #Base); \ } \ }; \ static ProxyType##UniqueID g_register_class_##UniqueID; \ } #define CLASS_LOADER_REGISTER_CLASS_INTERNAL_1(Derived, Base, UniqueID) \ CLASS_LOADER_REGISTER_CLASS_INTERNAL(Derived, Base, UniqueID) // register class macro #define CLASS_LOADER_REGISTER_CLASS(Derived, Base) \ CLASS_LOADER_REGISTER_CLASS_INTERNAL_1(Derived, Base, __COUNTER__) #endif // CYBER_CLASS_LOADER_CLASS_LOADER_REGISTER_MACRO_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/class_loader.h" #include <iostream> #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/class_loader/class_loader_manager.h" #include "cyber/class_loader/test/base.h" #include "cyber/cyber.h" const char LIBRARY_1[] = "/apollo/bazel-bin/cyber/class_loader/test/libplugin1.so"; const char LIBRARY_2[] = "/apollo/bazel-bin/cyber/class_loader/test/libplugin2.so"; using apollo::cyber::class_loader::ClassLoader; using apollo::cyber::class_loader::ClassLoaderManager; using apollo::cyber::class_loader::utility::IsLibraryLoadedByAnybody; TEST(ClassLoaderTest, createClassObj) { ClassLoader loader1(LIBRARY_1); EXPECT_EQ(LIBRARY_1, loader1.GetLibraryPath()); auto rect_obj = loader1.CreateClassObj<Base>("Rect"); EXPECT_NE(nullptr, rect_obj); rect_obj->DoSomething(); EXPECT_EQ(nullptr, loader1.CreateClassObj<Base>("Xeee")); SUCCEED(); } TEST(ClassLoaderTest, loadLibCounts) { ClassLoader loader1(LIBRARY_1); ASSERT_TRUE(loader1.IsLibraryLoaded()); loader1.LoadLibrary(); loader1.LoadLibrary(); ASSERT_TRUE(loader1.IsLibraryLoaded()); loader1.UnloadLibrary(); ASSERT_TRUE(loader1.IsLibraryLoaded()); loader1.UnloadLibrary(); ASSERT_TRUE(loader1.IsLibraryLoaded()); loader1.UnloadLibrary(); ASSERT_FALSE(loader1.IsLibraryLoaded()); loader1.UnloadLibrary(); ASSERT_FALSE(loader1.IsLibraryLoaded()); loader1.LoadLibrary(); ASSERT_TRUE(loader1.IsLibraryLoaded()); SUCCEED(); } TEST(ClassLoaderTest, multiTimesLoadunload) { ClassLoader loader1(LIBRARY_1); ASSERT_TRUE(loader1.LoadLibrary()); loader1.LoadLibrary(); ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1)); loader1.UnloadLibrary(); ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1)); loader1.UnloadLibrary(); ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1)); loader1.UnloadLibrary(); ASSERT_FALSE(IsLibraryLoadedByAnybody(LIBRARY_1)); } TEST(ClassLoaderManagerTest, testClassLoaderManager) { ClassLoaderManager loader_mgr; ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1)); ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_2)); for (int i = 0; i < 2; ++i) { loader_mgr.CreateClassObj<Base>("Rect")->DoSomething(); loader_mgr.CreateClassObj<Base>("Circle")->DoSomething(); loader_mgr.CreateClassObj<Base>("Apple")->DoSomething(); } auto pear_obj = loader_mgr.CreateClassObj<Base>("Pear", LIBRARY_2); EXPECT_NE(nullptr, pear_obj); pear_obj->DoSomething(); auto null_obj = loader_mgr.CreateClassObj<Base>("Pear", LIBRARY_1); EXPECT_EQ(nullptr, null_obj); auto null_obj1 = loader_mgr.CreateClassObj<Base>("ClassNull", "libNull.so"); EXPECT_EQ(nullptr, null_obj1); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Rect")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Circle")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Triangle")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Star")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Apple")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Pear")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Banana")); EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Peach")); EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Hamburger")); EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Cake")); EXPECT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1)); SUCCEED(); } void CreateObj(ClassLoaderManager* loader) { std::vector<std::string> classes = loader->GetValidClassNames<Base>(); for (unsigned int i = 0; i < classes.size(); i++) { loader->CreateClassObj<Base>(classes[i])->DoSomething(); } } TEST(ClassLoaderTest, createObjThreadSafety) { ClassLoaderManager loader_mgr; ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1)); ASSERT_TRUE(loader_mgr.IsLibraryValid(LIBRARY_1)); std::vector<std::thread*> client_threads; for (unsigned int i = 0; i < 100; i++) { client_threads.emplace_back( new std::thread(std::bind(&CreateObj, &loader_mgr))); } for (unsigned int i = 0; i < client_threads.size(); i++) { client_threads[i]->join(); } for (unsigned int i = 0; i < client_threads.size(); i++) { delete (client_threads[i]); } } void LoadLib(ClassLoaderManager* loaderMgr) { loaderMgr->LoadLibrary(LIBRARY_1); ASSERT_TRUE(loaderMgr->IsLibraryValid(LIBRARY_1)); } TEST(ClassLoaderTest, loadLibThreadSafety) { ClassLoaderManager loaderMgr; std::vector<std::thread*> client_threads; for (unsigned int i = 0; i < 100; i++) { client_threads.emplace_back( new std::thread(std::bind(&LoadLib, &loaderMgr))); } for (unsigned int i = 0; i < client_threads.size(); i++) { client_threads[i]->join(); } ASSERT_TRUE(loaderMgr.IsLibraryValid(LIBRARY_1)); for (unsigned int i = 0; i < client_threads.size(); i++) { delete (client_threads[i]); } loaderMgr.UnloadAllLibrary(); ASSERT_FALSE(loaderMgr.IsLibraryValid(LIBRARY_1)); } class InvalidBaseClass {}; TEST(ClassLoaderTest, util_test) { ClassLoader loader1(LIBRARY_1); apollo::cyber::class_loader::utility::LoadLibrary("1", &loader1); apollo::cyber::class_loader::utility::UnloadLibrary("1", nullptr); apollo::cyber::class_loader::utility::IsLibraryLoaded(LIBRARY_1, &loader1); apollo::cyber::class_loader::utility::IsLibraryLoaded(LIBRARY_2, &loader1); } int main(int argc, char** argv) { apollo::cyber::Init(argv[0]); testing::InitGoogleTest(&argc, argv); const int output = RUN_ALL_TESTS(); google::protobuf::ShutdownProtobufLibrary(); return output; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader_manager.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_CLASS_LOADER_MANAGER_H_ #define CYBER_CLASS_LOADER_CLASS_LOADER_MANAGER_H_ #include <map> #include <memory> #include <mutex> #include <string> #include <vector> #include "cyber/class_loader/class_loader.h" namespace apollo { namespace cyber { namespace class_loader { class ClassLoaderManager { public: ClassLoaderManager(); virtual ~ClassLoaderManager(); bool LoadLibrary(const std::string& library_path); void UnloadAllLibrary(); bool IsLibraryValid(const std::string& library_path); template <typename Base> std::shared_ptr<Base> CreateClassObj(const std::string& class_name); template <typename Base> std::shared_ptr<Base> CreateClassObj(const std::string& class_name, const std::string& library_path); template <typename Base> bool IsClassValid(const std::string& class_name); template <typename Base> std::vector<std::string> GetValidClassNames(); private: ClassLoader* GetClassLoaderByLibPath(const std::string& library_path); std::vector<ClassLoader*> GetAllValidClassLoaders(); std::vector<std::string> GetAllValidLibPath(); int UnloadLibrary(const std::string& library_path); private: std::mutex libpath_loader_map_mutex_; std::map<std::string, ClassLoader*> libpath_loader_map_; }; template <typename Base> std::shared_ptr<Base> ClassLoaderManager::CreateClassObj( const std::string& class_name) { std::vector<ClassLoader*> class_loaders = GetAllValidClassLoaders(); for (auto class_loader : class_loaders) { if (class_loader->IsClassValid<Base>(class_name)) { return (class_loader->CreateClassObj<Base>(class_name)); } } AERROR << "Invalid class name: " << class_name; return std::shared_ptr<Base>(); } template <typename Base> std::shared_ptr<Base> ClassLoaderManager::CreateClassObj( const std::string& class_name, const std::string& library_path) { ClassLoader* loader = GetClassLoaderByLibPath(library_path); if (loader) { return (loader->CreateClassObj<Base>(class_name)); } AERROR << "Could not create classobj, there is no ClassLoader in: " << class_name; return std::shared_ptr<Base>(); } template <typename Base> bool ClassLoaderManager::IsClassValid(const std::string& class_name) { std::vector<std::string> valid_classes = GetValidClassNames<Base>(); return (valid_classes.end() != std::find(valid_classes.begin(), valid_classes.end(), class_name)); } template <typename Base> std::vector<std::string> ClassLoaderManager::GetValidClassNames() { std::vector<std::string> valid_classes; for (auto class_loader : GetAllValidClassLoaders()) { std::vector<std::string> class_loaders = class_loader->GetValidClassNames<Base>(); valid_classes.insert(valid_classes.end(), class_loaders.begin(), class_loaders.end()); } return valid_classes; } } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_CLASS_LOADER_MANAGER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/class_loader.h" namespace apollo { namespace cyber { namespace class_loader { ClassLoader::ClassLoader(const std::string& library_path) : library_path_(library_path), loadlib_ref_count_(0), classobj_ref_count_(0) { LoadLibrary(); } ClassLoader::~ClassLoader() { UnloadLibrary(); } bool ClassLoader::IsLibraryLoaded() { return utility::IsLibraryLoaded(library_path_, this); } bool ClassLoader::LoadLibrary() { std::lock_guard<std::mutex> lck(loadlib_ref_count_mutex_); ++loadlib_ref_count_; AINFO << "Begin LoadLibrary: " << library_path_; return utility::LoadLibrary(library_path_, this); } int ClassLoader::UnloadLibrary() { std::lock_guard<std::mutex> lckLib(loadlib_ref_count_mutex_); std::lock_guard<std::mutex> lckObj(classobj_ref_count_mutex_); if (classobj_ref_count_ > 0) { AINFO << "There are still classobjs have not been deleted, " "classobj_ref_count_: " << classobj_ref_count_; } else { --loadlib_ref_count_; if (loadlib_ref_count_ == 0) { utility::UnloadLibrary(library_path_, this); } else { if (loadlib_ref_count_ < 0) { loadlib_ref_count_ = 0; } } } return loadlib_ref_count_; } const std::string ClassLoader::GetLibraryPath() const { return library_path_; } } // namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_class_loader_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "class_loader", srcs = ["class_loader.cc"], hdrs = ["class_loader.h"], alwayslink = True, deps = [ ":class_loader_register_macro", "//cyber/class_loader/shared_library", "//cyber/class_loader/utility:class_factory", "//cyber/class_loader/utility:class_loader_utility", "//cyber/common:log", ], ) cc_library( name = "class_loader_register_macro", hdrs = ["class_loader_register_macro.h"], deps = [ "//cyber/class_loader/utility:class_loader_utility", ], ) cc_library( name = "class_loader_manager", srcs = ["class_loader_manager.cc"], hdrs = ["class_loader_manager.h"], alwayslink = True, deps = [ ":class_loader", ], ) cc_test( name = "class_loader_test", size = "small", srcs = ["class_loader_test.cc"], data = [ "//cyber/class_loader/test:plugin1", "//cyber/class_loader/test:plugin2", ], deps = [ "//cyber", "//cyber/class_loader/test:base", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/class_loader/class_loader_manager.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/class_loader_manager.h" namespace apollo { namespace cyber { namespace class_loader { ClassLoaderManager::ClassLoaderManager() {} ClassLoaderManager::~ClassLoaderManager() {} ClassLoader* ClassLoaderManager::GetClassLoaderByLibPath( const std::string& library_path) { return libpath_loader_map_[library_path]; } std::vector<ClassLoader*> ClassLoaderManager::GetAllValidClassLoaders() { std::vector<ClassLoader*> class_loaders; for (auto& lib_class_loader : libpath_loader_map_) { class_loaders.emplace_back(lib_class_loader.second); } return class_loaders; } std::vector<std::string> ClassLoaderManager::GetAllValidLibPath() { std::vector<std::string> libpath; for (auto& lib_class_loader : libpath_loader_map_) { if (lib_class_loader.second != nullptr) { libpath.emplace_back(lib_class_loader.first); } } return libpath; } bool ClassLoaderManager::IsLibraryValid(const std::string& library_name) { std::vector<std::string> valid_libraries = GetAllValidLibPath(); return (valid_libraries.end() != std::find(valid_libraries.begin(), valid_libraries.end(), library_name)); } bool ClassLoaderManager::LoadLibrary(const std::string& library_path) { std::lock_guard<std::mutex> lck(libpath_loader_map_mutex_); if (!IsLibraryValid(library_path)) { libpath_loader_map_[library_path] = new class_loader::ClassLoader(library_path); } return IsLibraryValid(library_path); } int ClassLoaderManager::UnloadLibrary(const std::string& library_path) { int num_remain_unload = 0; if (IsLibraryValid(library_path)) { ClassLoader* class_loader = GetClassLoaderByLibPath(library_path); if ((num_remain_unload = class_loader->UnloadLibrary()) == 0) { libpath_loader_map_[library_path] = nullptr; delete class_loader; } } return num_remain_unload; } void ClassLoaderManager::UnloadAllLibrary() { std::vector<std::string> valid_libraries = GetAllValidLibPath(); for (auto& lib : valid_libraries) { UnloadLibrary(lib); } } } // namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/test/plugin1.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <iostream> #include "cyber/class_loader/class_loader.h" #include "cyber/class_loader/test/base.h" class Circle : public Base { public: virtual void DoSomething() { std::cout << "I am Circle" << std::endl; } }; class Rect : public Base { public: virtual void DoSomething() { std::cout << "I am Rect" << std::endl; } ~Rect() {} }; class Triangle : public Base { public: virtual void DoSomething() { std::cout << "I am Triangle" << std::endl; } }; class Star : public Base { public: virtual void DoSomething() { std::cout << "I am Star" << std::endl; } }; CLASS_LOADER_REGISTER_CLASS(Circle, Base); CLASS_LOADER_REGISTER_CLASS(Rect, Base); CLASS_LOADER_REGISTER_CLASS(Triangle, Base); CLASS_LOADER_REGISTER_CLASS(Star, Base);
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/test/plugin2.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <iostream> #include "cyber/class_loader/class_loader.h" #include "cyber/class_loader/test/base.h" class Apple : public Base { public: virtual void DoSomething() { std::cout << "I am Apple" << std::endl; } }; class Pear : public Base { public: virtual void DoSomething() { std::cout << "I am Pear!!!" << std::endl; } }; class Banana : public Base { public: virtual void DoSomething() { std::cout << "I am Banana" << std::endl; } }; class Peach : public Base { public: virtual void DoSomething() { std::cout << "I am Peach!!!" << std::endl; } }; CLASS_LOADER_REGISTER_CLASS(Apple, Base); CLASS_LOADER_REGISTER_CLASS(Pear, Base); CLASS_LOADER_REGISTER_CLASS(Banana, Base); CLASS_LOADER_REGISTER_CLASS(Peach, Base);
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/test/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "base", testonly = True, hdrs = ["base.h"], ) cc_library( name = "plugin1", testonly = True, srcs = ["plugin1.cc"], deps = [ ":base", "//cyber/class_loader:class_loader_manager", ], ) cc_library( name = "plugin2", testonly = True, srcs = ["plugin2.cc"], deps = [ ":base", "//cyber/class_loader:class_loader_manager", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/test/base.h
/****************************************************************************** * Copyright 201 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_TEST_BASE_H_ #define CYBER_CLASS_LOADER_TEST_BASE_H_ class Base { public: virtual void DoSomething() = 0; virtual ~Base() {} }; #endif // CYBER_CLASS_LOADER_TEST_BASE_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/shared_library.h
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ // // Adapted from poco/Foundation/include/Poco/SharedLibrary.h // // Definition of the SharedLibrary class. // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef CYBER_CLASS_LOADER_SHARED_LIBRARY_SHARED_LIBRARY_H_ #define CYBER_CLASS_LOADER_SHARED_LIBRARY_SHARED_LIBRARY_H_ #include <mutex> #include <string> #include "cyber/class_loader/shared_library/exceptions.h" namespace apollo { namespace cyber { namespace class_loader { // The SharedLibrary class dynamically loads shared libraries at run-time. class SharedLibrary { public: enum Flags { // On platforms that use dlopen(), use RTLD_GLOBAL. This is the default // if no flags are given. SHLIB_GLOBAL = 1, // On platforms that use dlopen(), use RTLD_LOCAL instead of RTLD_GLOBAL. // // Note that if this flag is specified, RTTI (including dynamic_cast and // throw) will not work for types defined in the shared library with GCC // and possibly other compilers as well. See // http://gcc.gnu.org/faq.html#dso for more information. SHLIB_LOCAL = 2, }; // Creates a SharedLibrary object. SharedLibrary() = default; // Destroys the SharedLibrary. The actual library // remains loaded. virtual ~SharedLibrary(); // Creates a SharedLibrary object and loads a library // from the given path. explicit SharedLibrary(const std::string& path); // Creates a SharedLibrary object and loads a library // from the given path, using the given flags. // See the Flags enumeration for valid values. SharedLibrary(const std::string& path, int flags); public: // Loads a shared library from the given path. // Throws a LibraryAlreadyLoadedException if // a library has already been loaded. // Throws a LibraryLoadException if the library // cannot be loaded. void Load(const std::string& path); // Loads a shared library from the given path, // using the given flags. See the Flags enumeration // for valid values. // Throws a LibraryAlreadyLoadedException if // a library has already been loaded. // Throws a LibraryLoadException if the library // cannot be loaded. void Load(const std::string& path, int flags); // Unloads a shared library. void Unload(); // Returns true iff a library has been loaded. bool IsLoaded(); // Returns true iff the loaded library contains // a symbol with the given name. bool HasSymbol(const std::string& name); // Returns the address of the symbol with // the given name. For functions, this // is the entry point of the function. // Throws a SymbolNotFoundException if the // symbol does not exist. void* GetSymbol(const std::string& name); // Returns the path of the library, as specified in a call // to load() or the constructor. inline const std::string& GetPath() const { return path_; } public: SharedLibrary(const SharedLibrary&) = delete; SharedLibrary& operator=(const SharedLibrary&) = delete; private: void* handle_ = nullptr; std::string path_; static std::mutex mutex_; }; } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_SHARED_LIBRARY_SHARED_LIBRARY_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/exceptions.h
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_SHARED_LIBRARY_EXCEPTIONS_H_ #define CYBER_CLASS_LOADER_SHARED_LIBRARY_EXCEPTIONS_H_ #include <stdexcept> #include <string> namespace apollo { namespace cyber { namespace class_loader { #define DECLARE_SHARED_LIBRARY_EXCEPTION(CLS, BASE) \ class CLS : public BASE { \ public: \ explicit CLS(const std::string& err_msg) : BASE(err_msg) {} \ ~CLS() throw() {} \ }; DECLARE_SHARED_LIBRARY_EXCEPTION(LibraryAlreadyLoadedException, std::runtime_error); DECLARE_SHARED_LIBRARY_EXCEPTION(LibraryLoadException, std::runtime_error); DECLARE_SHARED_LIBRARY_EXCEPTION(SymbolNotFoundException, std::runtime_error); } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_SHARED_LIBRARY_EXCEPTIONS_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/sample.cc
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/shared_library/sample.h" #include <cmath> int sample_add(int x, int y) { return x + y; } double sample_sin(double x) { return std::sin(x); }
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/shared_library_test.cc
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/shared_library/shared_library.h" #include <cmath> #include "gtest/gtest.h" namespace { const std::string& SAMPLE_LIB = "/apollo/bazel-bin/cyber/class_loader/shared_library/libsample.so"; constexpr double epsilon = 1.0e-8; } // namespace namespace apollo { namespace cyber { namespace class_loader { TEST(SharedLibraryTest, symbol_test_1) { auto shared_lib = std::make_shared<SharedLibrary>(); EXPECT_TRUE(shared_lib->GetPath().empty()); EXPECT_FALSE(shared_lib->IsLoaded()); EXPECT_NO_THROW(shared_lib->Load(SAMPLE_LIB)); EXPECT_TRUE(shared_lib->IsLoaded()); EXPECT_THROW(shared_lib->Load(SAMPLE_LIB), LibraryAlreadyLoadedException); EXPECT_TRUE(shared_lib->HasSymbol("sample_add")); auto symbol = shared_lib->GetSymbol("sample_add"); EXPECT_TRUE(symbol != nullptr); typedef int (*BinaryFunc)(int, int); auto pf = reinterpret_cast<BinaryFunc>(symbol); EXPECT_EQ(pf(3, 5), 8); shared_lib->Unload(); } TEST(SharedLibraryTest, symbol_test_2) { auto shared_lib = std::make_shared<SharedLibrary>(SAMPLE_LIB); EXPECT_TRUE(shared_lib->IsLoaded()); typedef double (*UnaryFunc)(double); auto symbol = shared_lib->GetSymbol("sample_sin"); EXPECT_TRUE(symbol != nullptr); auto sample_sin = reinterpret_cast<UnaryFunc>(symbol); EXPECT_NEAR(sample_sin(M_PI / 2), 1.0, epsilon); shared_lib->Unload(); } } // namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/shared_library.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ // // Adapted from poco/Foundation/src/SharedLibrary_UNIX.cpp // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "cyber/class_loader/shared_library/shared_library.h" #include <dlfcn.h> namespace apollo { namespace cyber { namespace class_loader { std::mutex SharedLibrary::mutex_; SharedLibrary::SharedLibrary(const std::string& path) { Load(path, 0); } SharedLibrary::SharedLibrary(const std::string& path, int flags) { Load(path, flags); } void SharedLibrary::Load(const std::string& path) { Load(path, 0); } void SharedLibrary::Load(const std::string& path, int flags) { std::lock_guard<std::mutex> lock(mutex_); if (handle_) throw LibraryAlreadyLoadedException(path); int real_flag = RTLD_LAZY; if (flags & SHLIB_LOCAL) { real_flag |= RTLD_LOCAL; } else { real_flag |= RTLD_GLOBAL; } handle_ = dlopen(path.c_str(), real_flag); if (!handle_) { const char* err = dlerror(); throw LibraryLoadException(err ? std::string(err) : path); } path_ = path; } void SharedLibrary::Unload() { std::lock_guard<std::mutex> lock(mutex_); if (handle_) { dlclose(handle_); handle_ = nullptr; } } bool SharedLibrary::IsLoaded() { std::lock_guard<std::mutex> lock(mutex_); return handle_ != nullptr; } bool SharedLibrary::HasSymbol(const std::string& name) { return GetSymbol(name) != nullptr; } void* SharedLibrary::GetSymbol(const std::string& name) { std::lock_guard<std::mutex> lock(mutex_); if (!handle_) return nullptr; void* result = dlsym(handle_, name.c_str()); if (!result) { throw SymbolNotFoundException(name); } return result; } SharedLibrary::~SharedLibrary() {} } // namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_class_loader_shared_library_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "shared_library", srcs = ["shared_library.cc"], hdrs = ["shared_library.h"], linkopts = ["-ldl"], deps = [ ":exceptions", ], ) cc_library( name = "exceptions", hdrs = ["exceptions.h"], ) cc_binary( name = "libsample.so", testonly = True, linkshared = True, linkstatic = False, visibility = ["//visibility:private"], deps = [ ":sample_lib", ], ) cc_library( name = "sample_lib", testonly = True, srcs = ["sample.cc"], hdrs = ["sample.h"], linkopts = ["-lm"], visibility = ["//visibility:private"], ) cc_test( name = "shared_library_test", size = "small", srcs = ["shared_library_test.cc"], data = [ ":libsample.so", ], deps = [ ":shared_library", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/shared_library/sample.h
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_SHARED_LIBRARY_SAMPLE_H_ #define CYBER_CLASS_LOADER_SHARED_LIBRARY_SAMPLE_H_ extern "C" int sample_add(int a, int b); extern "C" double sample_sin(double x); #endif // CYBER_CLASS_LOADER_SHARED_LIBRARY_SAMPLE_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/utility/class_loader_utility.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_UTILITY_CLASS_LOADER_UTILITY_H_ #define CYBER_CLASS_LOADER_UTILITY_CLASS_LOADER_UTILITY_H_ #include <cassert> #include <cstdio> #include <map> #include <memory> #include <mutex> #include <string> #include <typeinfo> #include <utility> #include <vector> #include "cyber/class_loader/shared_library/shared_library.h" #include "cyber/class_loader/utility/class_factory.h" #include "cyber/common/log.h" /** * class register implement */ namespace apollo { namespace cyber { namespace class_loader { class ClassLoader; namespace utility { using SharedLibraryPtr = std::shared_ptr<SharedLibrary>; using ClassClassFactoryMap = std::map<std::string, utility::AbstractClassFactoryBase*>; using BaseToClassFactoryMapMap = std::map<std::string, ClassClassFactoryMap>; using LibPathSharedLibVector = std::vector<std::pair<std::string, SharedLibraryPtr>>; using ClassFactoryVector = std::vector<AbstractClassFactoryBase*>; BaseToClassFactoryMapMap& GetClassFactoryMapMap(); std::recursive_mutex& GetClassFactoryMapMapMutex(); LibPathSharedLibVector& GetLibPathSharedLibVector(); std::recursive_mutex& GetLibPathSharedLibMutex(); ClassClassFactoryMap& GetClassFactoryMapByBaseClass( const std::string& typeid_base_class_name); std::string GetCurLoadingLibraryName(); void SetCurLoadingLibraryName(const std::string& library_name); ClassLoader* GetCurActiveClassLoader(); void SetCurActiveClassLoader(ClassLoader* loader); bool IsLibraryLoaded(const std::string& library_path, ClassLoader* loader); bool IsLibraryLoadedByAnybody(const std::string& library_path); bool LoadLibrary(const std::string& library_path, ClassLoader* loader); void UnloadLibrary(const std::string& library_path, ClassLoader* loader); template <typename Derived, typename Base> void RegisterClass(const std::string& class_name, const std::string& base_class_name); template <typename Base> Base* CreateClassObj(const std::string& class_name, ClassLoader* loader); template <typename Base> std::vector<std::string> GetValidClassNames(ClassLoader* loader); template <typename Derived, typename Base> void RegisterClass(const std::string& class_name, const std::string& base_class_name) { AINFO << "registerclass:" << class_name << "," << base_class_name << "," << GetCurLoadingLibraryName(); utility::AbstractClassFactory<Base>* new_class_factory_obj = new utility::ClassFactory<Derived, Base>(class_name, base_class_name); new_class_factory_obj->AddOwnedClassLoader(GetCurActiveClassLoader()); new_class_factory_obj->SetRelativeLibraryPath(GetCurLoadingLibraryName()); GetClassFactoryMapMapMutex().lock(); ClassClassFactoryMap& factory_map = GetClassFactoryMapByBaseClass(typeid(Base).name()); factory_map[class_name] = new_class_factory_obj; GetClassFactoryMapMapMutex().unlock(); } template <typename Base> Base* CreateClassObj(const std::string& class_name, ClassLoader* loader) { GetClassFactoryMapMapMutex().lock(); ClassClassFactoryMap& factoryMap = GetClassFactoryMapByBaseClass(typeid(Base).name()); AbstractClassFactory<Base>* factory = nullptr; if (factoryMap.find(class_name) != factoryMap.end()) { factory = dynamic_cast<utility::AbstractClassFactory<Base>*>( factoryMap[class_name]); } GetClassFactoryMapMapMutex().unlock(); Base* classobj = nullptr; if (factory && factory->IsOwnedBy(loader)) { classobj = factory->CreateObj(); } return classobj; } template <typename Base> std::vector<std::string> GetValidClassNames(ClassLoader* loader) { std::lock_guard<std::recursive_mutex> lck(GetClassFactoryMapMapMutex()); ClassClassFactoryMap& factoryMap = GetClassFactoryMapByBaseClass(typeid(Base).name()); std::vector<std::string> classes; for (auto& class_factory : factoryMap) { AbstractClassFactoryBase* factory = class_factory.second; if (factory && factory->IsOwnedBy(loader)) { classes.emplace_back(class_factory.first); } } return classes; } } // namespace utility } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_UTILITY_CLASS_LOADER_UTILITY_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/utility/class_factory.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_CLASS_LOADER_UTILITY_CLASS_FACTORY_H_ #define CYBER_CLASS_LOADER_UTILITY_CLASS_FACTORY_H_ #include <string> #include <typeinfo> #include <vector> namespace apollo { namespace cyber { namespace class_loader { class ClassLoader; namespace utility { class AbstractClassFactoryBase { public: AbstractClassFactoryBase(const std::string& class_name, const std::string& base_class_name); virtual ~AbstractClassFactoryBase(); void SetRelativeLibraryPath(const std::string& library_path); void AddOwnedClassLoader(ClassLoader* loader); void RemoveOwnedClassLoader(const ClassLoader* loader); bool IsOwnedBy(const ClassLoader* loader); bool IsOwnedByAnybody(); std::vector<ClassLoader*> GetRelativeClassLoaders(); const std::string GetRelativeLibraryPath() const; const std::string GetBaseClassName() const; const std::string GetClassName() const; protected: std::vector<ClassLoader*> relative_class_loaders_; std::string relative_library_path_; std::string base_class_name_; std::string class_name_; }; template <typename Base> class AbstractClassFactory : public AbstractClassFactoryBase { public: AbstractClassFactory(const std::string& class_name, const std::string& base_class_name) : AbstractClassFactoryBase(class_name, base_class_name) {} virtual Base* CreateObj() const = 0; private: AbstractClassFactory(); AbstractClassFactory(const AbstractClassFactory&); AbstractClassFactory& operator=(const AbstractClassFactory&); }; template <typename ClassObject, typename Base> class ClassFactory : public AbstractClassFactory<Base> { public: ClassFactory(const std::string& class_name, const std::string& base_class_name) : AbstractClassFactory<Base>(class_name, base_class_name) {} Base* CreateObj() const { return new ClassObject; } }; } // namespace utility } // namespace class_loader } // namespace cyber } // namespace apollo #endif // CYBER_CLASS_LOADER_UTILITY_CLASS_FACTORY_H_
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/utility/class_loader_utility.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/utility/class_loader_utility.h" namespace apollo { namespace cyber { namespace class_loader { namespace utility { std::recursive_mutex& GetClassFactoryMapMapMutex() { static std::recursive_mutex m; return m; } std::recursive_mutex& GetLibPathSharedLibMutex() { static std::recursive_mutex m; return m; } BaseToClassFactoryMapMap& GetClassFactoryMapMap() { static BaseToClassFactoryMapMap instance; return instance; } LibPathSharedLibVector& GetLibPathSharedLibVector() { static LibPathSharedLibVector instance; return instance; } ClassClassFactoryMap& GetClassFactoryMapByBaseClass( const std::string& typeid_base_class_name) { BaseToClassFactoryMapMap& factoryMapMap = GetClassFactoryMapMap(); std::string base_class_name = typeid_base_class_name; if (factoryMapMap.find(base_class_name) == factoryMapMap.end()) { factoryMapMap[base_class_name] = ClassClassFactoryMap(); } return factoryMapMap[base_class_name]; } std::string& GetCurLoadingLibraryNameReference() { static std::string library_name; return library_name; } std::string GetCurLoadingLibraryName() { return GetCurLoadingLibraryNameReference(); } void SetCurLoadingLibraryName(const std::string& library_name) { std::string& library_name_ref = GetCurLoadingLibraryNameReference(); library_name_ref = library_name; } ClassLoader*& GetCurActiveClassLoaderReference() { static ClassLoader* loader = nullptr; return loader; } ClassLoader* GetCurActiveClassLoader() { return (GetCurActiveClassLoaderReference()); } void SetCurActiveClassLoader(ClassLoader* loader) { ClassLoader*& loader_ref = GetCurActiveClassLoaderReference(); loader_ref = loader; } ClassFactoryVector GetAllClassFactoryObjects( const ClassClassFactoryMap& factories) { ClassFactoryVector all_class_factory_objs; for (auto& class_factory : factories) { all_class_factory_objs.emplace_back(class_factory.second); } return all_class_factory_objs; } ClassFactoryVector GetAllClassFactoryObjects() { std::lock_guard<std::recursive_mutex> lck(GetClassFactoryMapMapMutex()); ClassFactoryVector all_class_factory_objs; BaseToClassFactoryMapMap& factory_map_map = GetClassFactoryMapMap(); for (auto& baseclass_map : factory_map_map) { ClassFactoryVector objs = GetAllClassFactoryObjects(baseclass_map.second); all_class_factory_objs.insert(all_class_factory_objs.end(), objs.begin(), objs.end()); } return all_class_factory_objs; } ClassFactoryVector GetAllClassFactoryObjectsOfLibrary( const std::string& library_path) { ClassFactoryVector all_class_factory_objs = GetAllClassFactoryObjects(); ClassFactoryVector library_class_factory_objs; for (auto& class_factory_obj : all_class_factory_objs) { if (class_factory_obj->GetRelativeLibraryPath() == library_path) { library_class_factory_objs.emplace_back(class_factory_obj); } } return library_class_factory_objs; } void DestroyClassFactoryObjectsOfLibrary( const std::string& library_path, const ClassLoader* class_loader, ClassClassFactoryMap* class_factory_map) { for (ClassClassFactoryMap::iterator itr = class_factory_map->begin(); itr != class_factory_map->end();) { AbstractClassFactoryBase* class_factory_object = itr->second; if (class_factory_object->GetRelativeLibraryPath() == library_path && class_factory_object->IsOwnedBy(class_loader)) { class_factory_object->RemoveOwnedClassLoader(class_loader); // when no anybody owner, delete && erase if (!class_factory_object->IsOwnedByAnybody()) { itr = class_factory_map->erase(itr); delete class_factory_object; } else { ++itr; } } else { ++itr; } } } void DestroyClassFactoryObjectsOfLibrary(const std::string& library_path, const ClassLoader* loader) { std::lock_guard<std::recursive_mutex> lck(GetClassFactoryMapMapMutex()); BaseToClassFactoryMapMap& factory_map_map = GetClassFactoryMapMap(); for (auto& baseclass_map : factory_map_map) { DestroyClassFactoryObjectsOfLibrary(library_path, loader, &baseclass_map.second); } } LibPathSharedLibVector::iterator FindLoadedLibrary( const std::string& library_path) { LibPathSharedLibVector& opened_libraries = GetLibPathSharedLibVector(); LibPathSharedLibVector::iterator itr; for (itr = opened_libraries.begin(); itr != opened_libraries.end(); ++itr) { if (itr->first == library_path) { break; } } return itr; } bool IsLibraryLoadedByAnybody(const std::string& library_path) { std::lock_guard<std::recursive_mutex> lck(GetLibPathSharedLibMutex()); LibPathSharedLibVector& opened_libraries = GetLibPathSharedLibVector(); LibPathSharedLibVector::iterator itr = FindLoadedLibrary(library_path); return itr != opened_libraries.end(); } bool IsLibraryLoaded(const std::string& library_path, ClassLoader* class_loader) { bool is_lib_loaded_by_anyone = IsLibraryLoadedByAnybody(library_path); ClassFactoryVector lib_class_factory_objs = GetAllClassFactoryObjectsOfLibrary(library_path); auto num_lib_class_factory_objs = lib_class_factory_objs.size(); if (is_lib_loaded_by_anyone && num_lib_class_factory_objs == 0) { return true; } ClassFactoryVector lib_loader_class_factory_objs; for (auto& class_factory_obj : lib_class_factory_objs) { if (class_factory_obj->IsOwnedBy(class_loader)) { lib_loader_class_factory_objs.emplace_back(class_factory_obj); } } auto num_lib_loader_class_factory_objs = lib_loader_class_factory_objs.size(); return (is_lib_loaded_by_anyone && (num_lib_loader_class_factory_objs <= num_lib_class_factory_objs)); } bool LoadLibrary(const std::string& library_path, ClassLoader* loader) { if (IsLibraryLoadedByAnybody(library_path)) { AINFO << "lib has been loaded by others,only attach to class factory obj." << library_path; ClassFactoryVector lib_class_factory_objs = GetAllClassFactoryObjectsOfLibrary(library_path); for (auto& class_factory_obj : lib_class_factory_objs) { class_factory_obj->AddOwnedClassLoader(loader); } return true; } SharedLibraryPtr shared_library = nullptr; static std::recursive_mutex loader_mutex; { std::lock_guard<std::recursive_mutex> lck(loader_mutex); try { SetCurActiveClassLoader(loader); SetCurLoadingLibraryName(library_path); shared_library = SharedLibraryPtr(new SharedLibrary(library_path)); } catch (const LibraryLoadException& e) { SetCurLoadingLibraryName(""); SetCurActiveClassLoader(nullptr); AERROR << "LibraryLoadException: " << e.what(); } catch (const LibraryAlreadyLoadedException& e) { SetCurLoadingLibraryName(""); SetCurActiveClassLoader(nullptr); AERROR << "LibraryAlreadyLoadedException: " << e.what(); } catch (const SymbolNotFoundException& e) { SetCurLoadingLibraryName(""); SetCurActiveClassLoader(nullptr); AERROR << "SymbolNotFoundException: " << e.what(); } SetCurLoadingLibraryName(""); SetCurActiveClassLoader(nullptr); } if (shared_library == nullptr) { AERROR << "shared library failed: " << library_path; return false; } auto num_lib_objs = GetAllClassFactoryObjectsOfLibrary(library_path).size(); if (num_lib_objs == 0) { AWARN << "Class factory objs counts is 0, maybe registerclass failed."; } std::lock_guard<std::recursive_mutex> lck(GetLibPathSharedLibMutex()); LibPathSharedLibVector& opened_libraries = GetLibPathSharedLibVector(); opened_libraries.emplace_back( std::pair<std::string, SharedLibraryPtr>(library_path, shared_library)); return true; } void UnloadLibrary(const std::string& library_path, ClassLoader* loader) { { std::lock_guard<std::recursive_mutex> lck(GetLibPathSharedLibMutex()); LibPathSharedLibVector& opened_libraries = GetLibPathSharedLibVector(); LibPathSharedLibVector::iterator itr = FindLoadedLibrary(library_path); if (itr == opened_libraries.end()) { AERROR << "Attempt to UnloadLibrary lib, but can't find lib: " << library_path; return; } std::string library_path = itr->first; try { DestroyClassFactoryObjectsOfLibrary(library_path, loader); if (GetAllClassFactoryObjectsOfLibrary(library_path).empty()) { itr->second->Unload(); itr = opened_libraries.erase(itr); } else { AWARN << "ClassFactory objects still remain in memory, meaning other" "class loaders are still using library:" << library_path; } } catch (const std::runtime_error& e) { AERROR << "Library unload error: " << e.what(); } } } } // End namespace utility } // End namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/utility/class_factory.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/class_loader/utility/class_factory.h" #include <algorithm> namespace apollo { namespace cyber { namespace class_loader { namespace utility { AbstractClassFactoryBase::AbstractClassFactoryBase( const std::string& class_name, const std::string& base_class_name) : relative_library_path_(""), base_class_name_(base_class_name), class_name_(class_name) {} AbstractClassFactoryBase::~AbstractClassFactoryBase() {} void AbstractClassFactoryBase::SetRelativeLibraryPath( const std::string& library_path) { relative_library_path_ = library_path; } void AbstractClassFactoryBase::AddOwnedClassLoader(ClassLoader* loader) { if (std::find(relative_class_loaders_.begin(), relative_class_loaders_.end(), loader) == relative_class_loaders_.end()) { relative_class_loaders_.emplace_back(loader); } } void AbstractClassFactoryBase::RemoveOwnedClassLoader( const ClassLoader* loader) { std::vector<ClassLoader*>::iterator itr = std::find( relative_class_loaders_.begin(), relative_class_loaders_.end(), loader); if (itr != relative_class_loaders_.end()) { relative_class_loaders_.erase(itr); } } bool AbstractClassFactoryBase::IsOwnedBy(const ClassLoader* loader) { std::vector<ClassLoader*>::iterator itr = std::find( relative_class_loaders_.begin(), relative_class_loaders_.end(), loader); return itr != relative_class_loaders_.end(); } bool AbstractClassFactoryBase::IsOwnedByAnybody() { return !relative_class_loaders_.empty(); } std::vector<ClassLoader*> AbstractClassFactoryBase::GetRelativeClassLoaders() { return relative_class_loaders_; } const std::string AbstractClassFactoryBase::GetRelativeLibraryPath() const { return relative_library_path_; } const std::string AbstractClassFactoryBase::GetBaseClassName() const { return base_class_name_; } const std::string AbstractClassFactoryBase::GetClassName() const { return class_name_; } } // namespace utility } // namespace class_loader } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/class_loader
apollo_public_repos/apollo/cyber/class_loader/utility/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_class_loader_utility_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "class_factory", srcs = ["class_factory.cc"], hdrs = ["class_factory.h"], alwayslink = True, ) cc_library( name = "class_loader_utility", srcs = ["class_loader_utility.cc"], hdrs = ["class_loader_utility.h"], deps = [ ":class_factory", "//cyber/class_loader/shared_library", "//cyber/common:log", ], alwayslink = True, ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/reader.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_READER_H_ #define CYBER_NODE_READER_H_ #include <algorithm> #include <list> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "cyber/proto/topology_change.pb.h" #include "cyber/blocker/blocker.h" #include "cyber/common/global_data.h" #include "cyber/croutine/routine_factory.h" #include "cyber/data/data_visitor.h" #include "cyber/node/reader_base.h" #include "cyber/scheduler/scheduler_factory.h" #include "cyber/service_discovery/topology_manager.h" #include "cyber/time/time.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { template <typename M0> using CallbackFunc = std::function<void(const std::shared_ptr<M0>&)>; using proto::RoleType; const uint32_t DEFAULT_PENDING_QUEUE_SIZE = 1; /** * @class Reader * @brief Reader subscribes a channel, it has two main functions: * 1. You can pass a `CallbackFunc` to handle the message then it arrived * 2. You can Observe messages that Blocker cached. Reader automatically push * the message to Blocker's `PublishQueue`, and we can use `Observe` to fetch * messages from `PublishQueue` to `ObserveQueue`. But, if you have set * CallbackFunc, you can ignore this. One Reader uses one `ChannelBuffer`, the * message we are handling is stored in ChannelBuffer Reader will Join the * topology when init and Leave the topology when shutdown * @warning To save resource, `ChannelBuffer` has limited length, * it's passed through the `pending_queue_size` param. pending_queue_size is * default set to 1, So, If you handle slower than writer sending, older * messages that are not handled will be lost. You can increase * `pending_queue_size` to resolve this problem. */ template <typename MessageT> class Reader : public ReaderBase { public: using BlockerPtr = std::unique_ptr<blocker::Blocker<MessageT>>; using ReceiverPtr = std::shared_ptr<transport::Receiver<MessageT>>; using ChangeConnection = typename service_discovery::Manager::ChangeConnection; using Iterator = typename std::list<std::shared_ptr<MessageT>>::const_iterator; /** * Constructor a Reader object. * @param role_attr is a protobuf message RoleAttributes, which includes the * channel name and other info. * @param reader_func is the callback function, when the message is received. * @param pending_queue_size is the max depth of message cache queue. * @warning the received messages is enqueue a queue,the queue's depth is * pending_queue_size */ explicit Reader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func = nullptr, uint32_t pending_queue_size = DEFAULT_PENDING_QUEUE_SIZE); virtual ~Reader(); /** * @brief Init Reader * * @return true if init successfully * @return false if init failed */ bool Init() override; /** * @brief Shutdown Reader */ void Shutdown() override; /** * @brief Get All data that `Blocker` stores */ void Observe() override; /** * @brief Clear `Blocker`'s data */ void ClearData() override; /** * @brief Query whether we have received data since last clear * * @return true if the reader has received data * @return false if the reader has not received data */ bool HasReceived() const override; /** * @brief Query whether the Reader has data to be handled * * @return true if blocker is empty * @return false if blocker has data */ bool Empty() const override; /** * @brief Get time interval of since last receive message * * @return double seconds delay */ double GetDelaySec() const override; /** * @brief Get pending_queue_size configuration * * @return uint32_t the value of pending queue size */ uint32_t PendingQueueSize() const override; /** * @brief Push `msg` to Blocker's `PublishQueue` * * @param msg message ptr to be pushed */ virtual void Enqueue(const std::shared_ptr<MessageT>& msg); /** * @brief Set Blocker's `PublishQueue`'s capacity to `depth` * * @param depth the value you want to set */ virtual void SetHistoryDepth(const uint32_t& depth); /** * @brief Get Blocker's `PublishQueue`'s capacity * * @return uint32_t depth of the history */ virtual uint32_t GetHistoryDepth() const; /** * @brief Get the latest message we `Observe` * * @return std::shared_ptr<MessageT> the latest message */ virtual std::shared_ptr<MessageT> GetLatestObserved() const; /** * @brief Get the oldest message we `Observe` * * @return std::shared_ptr<MessageT> the oldest message */ virtual std::shared_ptr<MessageT> GetOldestObserved() const; /** * @brief Get the begin iterator of `ObserveQueue`, used to traverse * * @return Iterator begin iterator */ virtual Iterator Begin() const { return blocker_->ObservedBegin(); } /** * @brief Get the end iterator of `ObserveQueue`, used to traverse * * @return Iterator begin iterator */ virtual Iterator End() const { return blocker_->ObservedEnd(); } /** * @brief Is there is at least one writer publish the channel that we * subscribes? * * @return true if the channel has writer * @return false if the channel has no writer */ bool HasWriter() override; /** * @brief Get all writers pushlish the channel we subscribes * * @param writers result vector of RoleAttributes */ void GetWriters(std::vector<proto::RoleAttributes>* writers) override; protected: double latest_recv_time_sec_ = -1.0; double second_to_lastest_recv_time_sec_ = -1.0; uint32_t pending_queue_size_; private: void JoinTheTopology(); void LeaveTheTopology(); void OnChannelChange(const proto::ChangeMsg& change_msg); CallbackFunc<MessageT> reader_func_; ReceiverPtr receiver_ = nullptr; std::string croutine_name_; BlockerPtr blocker_ = nullptr; ChangeConnection change_conn_; service_discovery::ChannelManagerPtr channel_manager_ = nullptr; }; template <typename MessageT> Reader<MessageT>::Reader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func, uint32_t pending_queue_size) : ReaderBase(role_attr), pending_queue_size_(pending_queue_size), reader_func_(reader_func) { blocker_.reset(new blocker::Blocker<MessageT>(blocker::BlockerAttr( role_attr.qos_profile().depth(), role_attr.channel_name()))); } template <typename MessageT> Reader<MessageT>::~Reader() { Shutdown(); } template <typename MessageT> void Reader<MessageT>::Enqueue(const std::shared_ptr<MessageT>& msg) { second_to_lastest_recv_time_sec_ = latest_recv_time_sec_; latest_recv_time_sec_ = Time::Now().ToSecond(); blocker_->Publish(msg); } template <typename MessageT> void Reader<MessageT>::Observe() { blocker_->Observe(); } template <typename MessageT> bool Reader<MessageT>::Init() { if (init_.exchange(true)) { return true; } std::function<void(const std::shared_ptr<MessageT>&)> func; if (reader_func_ != nullptr) { func = [this](const std::shared_ptr<MessageT>& msg) { this->Enqueue(msg); this->reader_func_(msg); }; } else { func = [this](const std::shared_ptr<MessageT>& msg) { this->Enqueue(msg); }; } auto sched = scheduler::Instance(); croutine_name_ = role_attr_.node_name() + "_" + role_attr_.channel_name(); auto dv = std::make_shared<data::DataVisitor<MessageT>>( role_attr_.channel_id(), pending_queue_size_); // Using factory to wrap templates. croutine::RoutineFactory factory = croutine::CreateRoutineFactory<MessageT>(std::move(func), dv); if (!sched->CreateTask(factory, croutine_name_)) { AERROR << "Create Task Failed!"; init_.store(false); return false; } receiver_ = ReceiverManager<MessageT>::Instance()->GetReceiver(role_attr_); this->role_attr_.set_id(receiver_->id().HashValue()); channel_manager_ = service_discovery::TopologyManager::Instance()->channel_manager(); JoinTheTopology(); return true; } template <typename MessageT> void Reader<MessageT>::Shutdown() { if (!init_.exchange(false)) { return; } LeaveTheTopology(); receiver_ = nullptr; channel_manager_ = nullptr; if (!croutine_name_.empty()) { scheduler::Instance()->RemoveTask(croutine_name_); } } template <typename MessageT> void Reader<MessageT>::JoinTheTopology() { // add listener change_conn_ = channel_manager_->AddChangeListener(std::bind( &Reader<MessageT>::OnChannelChange, this, std::placeholders::_1)); // get peer writers const std::string& channel_name = this->role_attr_.channel_name(); std::vector<proto::RoleAttributes> writers; channel_manager_->GetWritersOfChannel(channel_name, &writers); for (auto& writer : writers) { receiver_->Enable(writer); } channel_manager_->Join(this->role_attr_, proto::RoleType::ROLE_READER, message::HasSerializer<MessageT>::value); } template <typename MessageT> void Reader<MessageT>::LeaveTheTopology() { channel_manager_->RemoveChangeListener(change_conn_); channel_manager_->Leave(this->role_attr_, proto::RoleType::ROLE_READER); } template <typename MessageT> void Reader<MessageT>::OnChannelChange(const proto::ChangeMsg& change_msg) { if (change_msg.role_type() != proto::RoleType::ROLE_WRITER) { return; } auto& writer_attr = change_msg.role_attr(); if (writer_attr.channel_name() != this->role_attr_.channel_name()) { return; } auto operate_type = change_msg.operate_type(); if (operate_type == proto::OperateType::OPT_JOIN) { receiver_->Enable(writer_attr); } else { receiver_->Disable(writer_attr); } } template <typename MessageT> bool Reader<MessageT>::HasReceived() const { return !blocker_->IsPublishedEmpty(); } template <typename MessageT> bool Reader<MessageT>::Empty() const { return blocker_->IsObservedEmpty(); } template <typename MessageT> double Reader<MessageT>::GetDelaySec() const { if (latest_recv_time_sec_ < 0) { return -1.0; } if (second_to_lastest_recv_time_sec_ < 0) { return Time::Now().ToSecond() - latest_recv_time_sec_; } return std::max((Time::Now().ToSecond() - latest_recv_time_sec_), (latest_recv_time_sec_ - second_to_lastest_recv_time_sec_)); } template <typename MessageT> uint32_t Reader<MessageT>::PendingQueueSize() const { return pending_queue_size_; } template <typename MessageT> std::shared_ptr<MessageT> Reader<MessageT>::GetLatestObserved() const { return blocker_->GetLatestObservedPtr(); } template <typename MessageT> std::shared_ptr<MessageT> Reader<MessageT>::GetOldestObserved() const { return blocker_->GetOldestObservedPtr(); } template <typename MessageT> void Reader<MessageT>::ClearData() { blocker_->ClearPublished(); blocker_->ClearObserved(); } template <typename MessageT> void Reader<MessageT>::SetHistoryDepth(const uint32_t& depth) { blocker_->set_capacity(depth); } template <typename MessageT> uint32_t Reader<MessageT>::GetHistoryDepth() const { return static_cast<uint32_t>(blocker_->capacity()); } template <typename MessageT> bool Reader<MessageT>::HasWriter() { if (!init_.load()) { return false; } return channel_manager_->HasWriter(role_attr_.channel_name()); } template <typename MessageT> void Reader<MessageT>::GetWriters(std::vector<proto::RoleAttributes>* writers) { if (writers == nullptr) { return; } if (!init_.load()) { return; } channel_manager_->GetWritersOfChannel(role_attr_.channel_name(), writers); } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_READER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/node_channel_impl.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_NODE_CHANNEL_IMPL_H_ #define CYBER_NODE_NODE_CHANNEL_IMPL_H_ #include <memory> #include <string> #include "cyber/proto/run_mode_conf.pb.h" #include "cyber/blocker/intra_reader.h" #include "cyber/blocker/intra_writer.h" #include "cyber/common/global_data.h" #include "cyber/message/message_traits.h" #include "cyber/node/reader.h" #include "cyber/node/writer.h" namespace apollo { namespace cyber { class Node; struct ReaderConfig { ///< configurations for a Reader ReaderConfig() { qos_profile.set_history(proto::QosHistoryPolicy::HISTORY_KEEP_LAST); qos_profile.set_depth(1); qos_profile.set_mps(0); qos_profile.set_reliability( proto::QosReliabilityPolicy::RELIABILITY_RELIABLE); qos_profile.set_durability(proto::QosDurabilityPolicy::DURABILITY_VOLATILE); pending_queue_size = DEFAULT_PENDING_QUEUE_SIZE; } ReaderConfig(const ReaderConfig& other) : channel_name(other.channel_name), qos_profile(other.qos_profile), pending_queue_size(other.pending_queue_size) {} std::string channel_name; //< channel reads proto::QosProfile qos_profile; //< the qos configuration /** * @brief configuration for responding ChannelBuffer. * Older messages will dropped if you have no time to handle */ uint32_t pending_queue_size; }; /** * @class NodeChannelImpl * @brief The implementation for Node to create Objects connected by Channels. * e.g. Channel Reader and Writer */ class NodeChannelImpl { friend class Node; public: using NodeManagerPtr = std::shared_ptr<service_discovery::NodeManager>; /** * @brief Construct a new Node Channel Impl object * * @param node_name node name */ explicit NodeChannelImpl(const std::string& node_name) : is_reality_mode_(true), node_name_(node_name) { node_attr_.set_host_name(common::GlobalData::Instance()->HostName()); node_attr_.set_host_ip(common::GlobalData::Instance()->HostIp()); node_attr_.set_process_id(common::GlobalData::Instance()->ProcessId()); node_attr_.set_node_name(node_name); uint64_t node_id = common::GlobalData::RegisterNode(node_name); node_attr_.set_node_id(node_id); is_reality_mode_ = common::GlobalData::Instance()->IsRealityMode(); if (is_reality_mode_) { node_manager_ = service_discovery::TopologyManager::Instance()->node_manager(); node_manager_->Join(node_attr_, RoleType::ROLE_NODE); } } /** * @brief Destroy the Node Channel Impl object */ virtual ~NodeChannelImpl() { if (is_reality_mode_) { node_manager_->Leave(node_attr_, RoleType::ROLE_NODE); node_manager_ = nullptr; } } /** * @brief get name of this node * * @return const std::string& actual node name */ const std::string& NodeName() const { return node_name_; } private: template <typename MessageT> auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>>; template <typename MessageT> auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>>; template <typename MessageT> auto CreateReader(const std::string& channel_name, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> auto CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func, uint32_t pending_queue_size = DEFAULT_PENDING_QUEUE_SIZE) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> auto CreateReader(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> void FillInAttr(proto::RoleAttributes* attr); bool is_reality_mode_; std::string node_name_; proto::RoleAttributes node_attr_; NodeManagerPtr node_manager_ = nullptr; }; template <typename MessageT> auto NodeChannelImpl::CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>> { if (!role_attr.has_channel_name() || role_attr.channel_name().empty()) { AERROR << "Can't create a writer with empty channel name!"; return nullptr; } proto::RoleAttributes new_attr(role_attr); FillInAttr<MessageT>(&new_attr); std::shared_ptr<Writer<MessageT>> writer_ptr = nullptr; if (!is_reality_mode_) { writer_ptr = std::make_shared<blocker::IntraWriter<MessageT>>(new_attr); } else { writer_ptr = std::make_shared<Writer<MessageT>>(new_attr); } RETURN_VAL_IF_NULL(writer_ptr, nullptr); RETURN_VAL_IF(!writer_ptr->Init(), nullptr); return writer_ptr; } template <typename MessageT> auto NodeChannelImpl::CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>> { proto::RoleAttributes role_attr; role_attr.set_channel_name(channel_name); return this->CreateWriter<MessageT>(role_attr); } template <typename MessageT> auto NodeChannelImpl::CreateReader(const std::string& channel_name, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>> { proto::RoleAttributes role_attr; role_attr.set_channel_name(channel_name); return this->template CreateReader<MessageT>(role_attr, reader_func); } template <typename MessageT> auto NodeChannelImpl::CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>> { proto::RoleAttributes role_attr; role_attr.set_channel_name(config.channel_name); role_attr.mutable_qos_profile()->CopyFrom(config.qos_profile); return this->template CreateReader<MessageT>(role_attr, reader_func, config.pending_queue_size); } template <typename MessageT> auto NodeChannelImpl::CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func, uint32_t pending_queue_size) -> std::shared_ptr<Reader<MessageT>> { if (!role_attr.has_channel_name() || role_attr.channel_name().empty()) { AERROR << "Can't create a reader with empty channel name!"; return nullptr; } proto::RoleAttributes new_attr(role_attr); FillInAttr<MessageT>(&new_attr); std::shared_ptr<Reader<MessageT>> reader_ptr = nullptr; if (!is_reality_mode_) { reader_ptr = std::make_shared<blocker::IntraReader<MessageT>>(new_attr, reader_func); } else { reader_ptr = std::make_shared<Reader<MessageT>>(new_attr, reader_func, pending_queue_size); } RETURN_VAL_IF_NULL(reader_ptr, nullptr); RETURN_VAL_IF(!reader_ptr->Init(), nullptr); return reader_ptr; } template <typename MessageT> auto NodeChannelImpl::CreateReader(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Reader<MessageT>> { return this->template CreateReader<MessageT>(role_attr, nullptr); } template <typename MessageT> void NodeChannelImpl::FillInAttr(proto::RoleAttributes* attr) { attr->set_host_name(node_attr_.host_name()); attr->set_host_ip(node_attr_.host_ip()); attr->set_process_id(node_attr_.process_id()); attr->set_node_name(node_attr_.node_name()); attr->set_node_id(node_attr_.node_id()); auto channel_id = GlobalData::RegisterChannel(attr->channel_name()); attr->set_channel_id(channel_id); if (!attr->has_message_type()) { attr->set_message_type(message::MessageType<MessageT>()); } if (!attr->has_proto_desc()) { std::string proto_desc(""); message::GetDescriptorString<MessageT>(attr->message_type(), &proto_desc); attr->set_proto_desc(proto_desc); } if (!attr->has_qos_profile()) { attr->mutable_qos_profile()->CopyFrom( transport::QosProfileConf::QOS_PROFILE_DEFAULT); } } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_NODE_CHANNEL_IMPL_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/node.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/node/node.h" #include "cyber/common/global_data.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { using proto::RoleType; Node::Node(const std::string& node_name, const std::string& name_space) : node_name_(node_name), name_space_(name_space) { node_channel_impl_.reset(new NodeChannelImpl(node_name)); node_service_impl_.reset(new NodeServiceImpl(node_name)); } Node::~Node() {} const std::string& Node::Name() const { return node_name_; } void Node::Observe() { for (auto& reader : readers_) { reader.second->Observe(); } } void Node::ClearData() { for (auto& reader : readers_) { reader.second->ClearData(); } } bool Node::DeleteReader(const std::string& channel_name) { std::lock_guard<std::mutex> lg(readers_mutex_); int result = readers_.erase(channel_name); if (1 == result) return true; return false; } bool Node::DeleteReader(const proto::RoleAttributes& role_attr) { std::lock_guard<std::mutex> lg(readers_mutex_); int result = readers_.erase(role_attr.channel_name()); if (1 == result) return true; return false; } bool Node::DeleteReader(const ReaderConfig& config) { std::lock_guard<std::mutex> lg(readers_mutex_); int result = readers_.erase(config.channel_name); if (1 == result) return true; return false; } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/node_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/node/node.h" #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/node/reader.h" #include "cyber/node/writer.h" namespace apollo { namespace cyber { using apollo::cyber::proto::Chatter; TEST(NodeTest, cases) { auto node = CreateNode("node_test"); EXPECT_EQ(node->Name(), "node_test"); proto::RoleAttributes attr; attr.set_channel_name("/node_test_channel"); auto channel_id = common::GlobalData::RegisterChannel(attr.channel_name()); attr.set_channel_id(channel_id); attr.mutable_qos_profile()->set_depth(10); auto reader = node->CreateReader<Chatter>(attr); EXPECT_TRUE(node->GetReader<Chatter>(attr.channel_name())); auto writer = node->CreateWriter<Chatter>(attr); auto server = node->CreateService<Chatter, Chatter>( "node_test_server", [](const std::shared_ptr<Chatter>& request, std::shared_ptr<Chatter>& response) { AINFO << "server: I am server"; static uint64_t id = 0; ++id; response->set_seq(id); response->set_timestamp(0); }); auto client = node->CreateClient<Chatter, Chatter>("node_test_server"); auto chatter_msg = std::make_shared<Chatter>(); chatter_msg->set_seq(0); chatter_msg->set_timestamp(0); auto res = client->SendRequest(chatter_msg); EXPECT_EQ(res->seq(), 1); node->Observe(); node->ClearData(); } } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/reader_base.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_READER_BASE_H_ #define CYBER_NODE_READER_BASE_H_ #include <atomic> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "cyber/common/macros.h" #include "cyber/common/util.h" #include "cyber/event/perf_event_cache.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { using apollo::cyber::common::GlobalData; using apollo::cyber::event::PerfEventCache; using apollo::cyber::event::TransPerf; /** * @class ReaderBase * @brief Base Class for Reader * Reader is identified by one apollo::cyber::proto::RoleAttribute, * it contains the channel_name, channel_id that we subscribe, * and host_name, process_id and node that we are located, * and qos that describes our transportation quality. */ class ReaderBase { public: explicit ReaderBase(const proto::RoleAttributes& role_attr) : role_attr_(role_attr), init_(false) {} virtual ~ReaderBase() {} /** * @brief Init the Reader object * * @return true if init successfully * @return false if init failed */ virtual bool Init() = 0; /** * @brief Shutdown the Reader object */ virtual void Shutdown() = 0; /** * @brief Clear local data */ virtual void ClearData() = 0; /** * @brief Get stored data */ virtual void Observe() = 0; /** * @brief Query whether the Reader has data to be handled * * @return true if data container is empty * @return false if data container has data */ virtual bool Empty() const = 0; /** * @brief Query whether we have received data since last clear * * @return true if the reader has received data * @return false if the reader has not received data */ virtual bool HasReceived() const = 0; /** * @brief Get time interval of since last receive message * * @return double seconds delay */ virtual double GetDelaySec() const = 0; /** * @brief Get the value of pending queue size * * @return uint32_t result value */ virtual uint32_t PendingQueueSize() const = 0; /** * @brief Query is there any writer that publish the subscribed channel * * @return true if there is at least one Writer publish the channel * @return false if there is no Writer publish the channel */ virtual bool HasWriter() { return false; } /** * @brief Get all writers pushlish the channel we subscribes * * @param writers result RoleAttributes vector */ virtual void GetWriters(std::vector<proto::RoleAttributes>* writers) {} /** * @brief Get Reader's Channel name * * @return const std::string& channel name */ const std::string& GetChannelName() const { return role_attr_.channel_name(); } /** * @brief Get Reader's Channel id * * @return uint64_t channel id */ uint64_t ChannelId() const { return role_attr_.channel_id(); } /** * @brief Get qos profile. You can see qos description * * @return const proto::QosProfile& result qos */ const proto::QosProfile& QosProfile() const { return role_attr_.qos_profile(); } /** * @brief Query whether the Reader is initialized * * @return true if the Reader has been inited * @return false if the Reader has not been inited */ bool IsInit() const { return init_.load(); } protected: proto::RoleAttributes role_attr_; std::atomic<bool> init_; }; /** * @brief One Channel is related to one Receiver. * ReceiverManager is in charge of attaching one Receiver to its responding * Channel. We pass a DataDispatche's callback func to this Receiver so when a * message is received, it will be push to the `ChannelBuffer`, and * `DataVisitor` will `Fetch` data and pass to `Reader`'s callback func * * @tparam MessageT Message Type. */ template <typename MessageT> class ReceiverManager { public: ~ReceiverManager() { receiver_map_.clear(); } /** * @brief Get the Receiver object * * @param role_attr the attribute that the Receiver has * @return std::shared_ptr<transport::Receiver<MessageT>> result Receiver */ auto GetReceiver(const proto::RoleAttributes& role_attr) -> typename std::shared_ptr<transport::Receiver<MessageT>>; private: std::unordered_map<std::string, typename std::shared_ptr<transport::Receiver<MessageT>>> receiver_map_; std::mutex receiver_map_mutex_; DECLARE_SINGLETON(ReceiverManager<MessageT>) }; /** * @brief Construct a new Receiver Manager< Message T>:: Receiver Manager object * * @tparam MessageT param */ template <typename MessageT> ReceiverManager<MessageT>::ReceiverManager() {} template <typename MessageT> auto ReceiverManager<MessageT>::GetReceiver( const proto::RoleAttributes& role_attr) -> typename std::shared_ptr<transport::Receiver<MessageT>> { std::lock_guard<std::mutex> lock(receiver_map_mutex_); // because multi reader for one channel will write datacache multi times, // so reader for datacache we use map to keep one instance for per channel const std::string& channel_name = role_attr.channel_name(); if (receiver_map_.count(channel_name) == 0) { receiver_map_[channel_name] = transport::Transport::Instance()->CreateReceiver<MessageT>( role_attr, [](const std::shared_ptr<MessageT>& msg, const transport::MessageInfo& msg_info, const proto::RoleAttributes& reader_attr) { (void)msg_info; (void)reader_attr; PerfEventCache::Instance()->AddTransportEvent( TransPerf::DISPATCH, reader_attr.channel_id(), msg_info.seq_num()); data::DataDispatcher<MessageT>::Instance()->Dispatch( reader_attr.channel_id(), msg); PerfEventCache::Instance()->AddTransportEvent( TransPerf::NOTIFY, reader_attr.channel_id(), msg_info.seq_num()); }); } return receiver_map_[channel_name]; } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_READER_BASE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/node_service_impl.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_NODE_SERVICE_IMPL_H_ #define CYBER_NODE_NODE_SERVICE_IMPL_H_ #include <memory> #include <string> #include <vector> #include "cyber/common/global_data.h" #include "cyber/service/client.h" #include "cyber/service/service.h" #include "cyber/service_discovery/topology_manager.h" namespace apollo { namespace cyber { class Node; /** * @class NodeServiceImpl * @brief The implementation for Node to create Objects connected by Param. * e.g. Param Server and Client */ class NodeServiceImpl { public: friend class Node; /** * @brief Construct a new Node Service Impl object * * @param node_name node name */ explicit NodeServiceImpl(const std::string& node_name) : node_name_(node_name) { attr_.set_host_name(common::GlobalData::Instance()->HostName()); attr_.set_process_id(common::GlobalData::Instance()->ProcessId()); attr_.set_node_name(node_name); auto node_id = common::GlobalData::RegisterNode(node_name); attr_.set_node_id(node_id); } /** * @brief Forbid default-constructor */ NodeServiceImpl() = delete; /** * @brief Destroy the Node Service Impl object * */ ~NodeServiceImpl() {} private: template <typename Request, typename Response> auto CreateService(const std::string& service_name, const typename Service<Request, Response>::ServiceCallback& service_callback) -> typename std::shared_ptr<Service<Request, Response>>; template <typename Request, typename Response> auto CreateClient(const std::string& service_name) -> typename std::shared_ptr<Client<Request, Response>>; std::vector<std::weak_ptr<ServiceBase>> service_list_; std::vector<std::weak_ptr<ClientBase>> client_list_; std::string node_name_; proto::RoleAttributes attr_; }; template <typename Request, typename Response> auto NodeServiceImpl::CreateService( const std::string& service_name, const typename Service<Request, Response>::ServiceCallback& service_callback) -> typename std::shared_ptr<Service<Request, Response>> { auto service_ptr = std::make_shared<Service<Request, Response>>( node_name_, service_name, service_callback); RETURN_VAL_IF(!service_ptr->Init(), nullptr); service_list_.emplace_back(service_ptr); attr_.set_service_name(service_name); auto service_id = common::GlobalData::RegisterService(service_name); attr_.set_service_id(service_id); service_discovery::TopologyManager::Instance()->service_manager()->Join( attr_, RoleType::ROLE_SERVER); return service_ptr; } template <typename Request, typename Response> auto NodeServiceImpl::CreateClient(const std::string& service_name) -> typename std::shared_ptr<Client<Request, Response>> { auto client_ptr = std::make_shared<Client<Request, Response>>(node_name_, service_name); RETURN_VAL_IF(!client_ptr->Init(), nullptr); client_list_.emplace_back(client_ptr); attr_.set_service_name(service_name); auto service_id = common::GlobalData::RegisterService(service_name); attr_.set_service_id(service_id); service_discovery::TopologyManager::Instance()->service_manager()->Join( attr_, RoleType::ROLE_CLIENT); return client_ptr; } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_NODE_SERVICE_IMPL_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/reader_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include "cyber/node/reader.h" #include <string> #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/cyber.h" #include "cyber/init.h" namespace apollo { namespace cyber { namespace reader { using proto::Chatter; auto callback = [](const std::shared_ptr<proto::Chatter>& msg) { AINFO << "msg size = " << msg->ByteSizeLong(); }; TEST(ReaderTest, test1) { proto::RoleAttributes role; { Reader<Chatter> r(role, callback, 0); EXPECT_EQ(r.PendingQueueSize(), 0); EXPECT_TRUE(r.GetChannelName().empty()); EXPECT_TRUE(r.Init()); EXPECT_TRUE(r.GetChannelName().empty()); EXPECT_TRUE(r.IsInit()); r.Observe(); EXPECT_FALSE(r.HasReceived()); EXPECT_TRUE(r.Empty()); EXPECT_LT(r.GetDelaySec(), 0); r.ClearData(); r.Shutdown(); } { Reader<Chatter> r(role, callback, 100); EXPECT_EQ(r.PendingQueueSize(), 100); EXPECT_TRUE(r.GetChannelName().empty()); EXPECT_TRUE(r.Init()); EXPECT_TRUE(r.GetChannelName().empty()); EXPECT_TRUE(r.IsInit()); r.Observe(); EXPECT_FALSE(r.HasReceived()); EXPECT_TRUE(r.Empty()); EXPECT_LT(r.GetDelaySec(), 0); r.ClearData(); r.Shutdown(); } auto qos = role.mutable_qos_profile(); qos->set_history(proto::QosHistoryPolicy::HISTORY_KEEP_LAST); qos->set_depth(1); qos->set_mps(0); qos->set_reliability(proto::QosReliabilityPolicy::RELIABILITY_RELIABLE); qos->set_durability(proto::QosDurabilityPolicy::DURABILITY_VOLATILE); role.set_channel_name("/chatter0"); { Reader<Chatter> r(role, nullptr, 100); EXPECT_EQ(r.PendingQueueSize(), 100); EXPECT_EQ(r.GetChannelName(), "/chatter0"); EXPECT_TRUE(r.Init()); EXPECT_EQ(r.GetChannelName(), "/chatter0"); EXPECT_TRUE(r.IsInit()); r.Observe(); EXPECT_FALSE(r.HasReceived()); EXPECT_TRUE(r.Empty()); EXPECT_LT(r.GetDelaySec(), 0); r.ClearData(); r.Shutdown(); } { Reader<Chatter> r(role, callback, 100); EXPECT_EQ(r.PendingQueueSize(), 100); EXPECT_EQ(r.GetChannelName(), "/chatter0"); EXPECT_TRUE(r.Init()); EXPECT_EQ(r.GetChannelName(), "/chatter0"); EXPECT_TRUE(r.IsInit()); r.Observe(); EXPECT_FALSE(r.HasReceived()); EXPECT_TRUE(r.Empty()); EXPECT_LT(r.GetDelaySec(), 0); r.ClearData(); r.Shutdown(); } } TEST(ReaderTest, test2) { proto::RoleAttributes role; auto qos = role.mutable_qos_profile(); qos->set_history(proto::QosHistoryPolicy::HISTORY_KEEP_LAST); qos->set_depth(0); qos->set_mps(0); qos->set_reliability(proto::QosReliabilityPolicy::RELIABILITY_RELIABLE); qos->set_durability(proto::QosDurabilityPolicy::DURABILITY_VOLATILE); role.set_channel_name("/chatter0"); Reader<Chatter> r(role, callback, 100); EXPECT_EQ(r.PendingQueueSize(), 100); EXPECT_EQ(r.GetChannelName(), "/chatter0"); EXPECT_TRUE(r.Init()); r.SetHistoryDepth(1); EXPECT_TRUE(r.Init()); { auto c = std::make_shared<Chatter>(); c->set_timestamp(Time::Now().ToNanosecond()); c->set_lidar_timestamp(Time::Now().ToNanosecond()); c->set_seq(1); c->set_content("ChatterMsg"); r.Enqueue(c); } EXPECT_EQ(r.GetHistoryDepth(), 1); EXPECT_GT(r.GetDelaySec(), 0); r.SetHistoryDepth(0); { auto c = std::make_shared<Chatter>(); c->set_timestamp(Time::Now().ToNanosecond()); c->set_lidar_timestamp(Time::Now().ToNanosecond()); c->set_seq(2); c->set_content("ChatterMsg"); r.Enqueue(c); } EXPECT_EQ(r.GetHistoryDepth(), 0); EXPECT_EQ(r.Begin(), r.End()); EXPECT_GT(r.GetDelaySec(), 0); r.SetHistoryDepth(3); { auto c = std::make_shared<Chatter>(); c->set_timestamp(Time::Now().ToNanosecond()); c->set_lidar_timestamp(Time::Now().ToNanosecond()); c->set_seq(3); c->set_content("ChatterMsg"); r.Enqueue(c); } { auto c = std::make_shared<Chatter>(); c->set_timestamp(Time::Now().ToNanosecond()); c->set_lidar_timestamp(Time::Now().ToNanosecond()); c->set_seq(4); c->set_content("ChatterMsg"); r.Enqueue(c); } { auto c = std::make_shared<Chatter>(); c->set_timestamp(Time::Now().ToNanosecond()); c->set_lidar_timestamp(Time::Now().ToNanosecond()); c->set_seq(5); c->set_content("ChatterMsg"); r.Enqueue(c); } EXPECT_EQ(r.GetHistoryDepth(), 3); auto latestMsg = r.GetLatestObserved(); auto oldestMsg = r.GetOldestObserved(); EXPECT_EQ(nullptr, latestMsg); EXPECT_EQ(nullptr, oldestMsg); EXPECT_EQ(r.Begin(), r.End()); r.Observe(); latestMsg = r.GetLatestObserved(); oldestMsg = r.GetOldestObserved(); EXPECT_EQ(latestMsg->seq(), 5); EXPECT_EQ(oldestMsg->seq(), 3); } } // namespace reader } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/node.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_NODE_H_ #define CYBER_NODE_NODE_H_ #include <map> #include <memory> #include <string> #include <utility> #include "cyber/node/node_channel_impl.h" #include "cyber/node/node_service_impl.h" namespace apollo { namespace cyber { template <typename M0, typename M1, typename M2, typename M3> class Component; class TimerComponent; /** * @class Node * @brief Node is the fundamental building block of Cyber RT. * every module contains and communicates through the node. * A module can have different types of communication by defining * read/write and/or service/client in a node. * @warning Duplicate name is not allowed in topo objects, such as node, * reader/writer, service/clinet in the topo. */ class Node { public: template <typename M0, typename M1, typename M2, typename M3> friend class Component; friend class TimerComponent; friend bool Init(const char*); friend std::unique_ptr<Node> CreateNode(const std::string&, const std::string&); virtual ~Node(); /** * @brief Get node's name. * @warning duplicate node name is not allowed in the topo. */ const std::string& Name() const; /** * @brief Create a Writer with specific message type. * * @tparam MessageT Message Type * @param role_attr is a protobuf message RoleAttributes, which includes the * channel name and other info. * @return std::shared_ptr<Writer<MessageT>> result Writer Object */ template <typename MessageT> auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>>; /** * @brief Create a Writer with specific message type. * * @tparam MessageT Message Type * @param channel_name the channel name to be published. * @return std::shared_ptr<Writer<MessageT>> result Writer Object */ template <typename MessageT> auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>>; /** * @brief Create a Reader with specific message type with channel name * qos and other configs used will be default * * @tparam MessageT Message Type * @param channel_name the channel of the reader subscribed. * @param reader_func invoked when message receive * invoked when the message is received. * @return std::shared_ptr<cyber::Reader<MessageT>> result Reader Object */ template <typename MessageT> auto CreateReader(const std::string& channel_name, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; /** * @brief Create a Reader with specific message type with reader config * * @tparam MessageT Message Type * @param config instance of `ReaderConfig`, * include channel name, qos and pending queue size * @param reader_func invoked when message receive * @return std::shared_ptr<cyber::Reader<MessageT>> result Reader Object */ template <typename MessageT> auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; /** * @brief Create a Reader object with `RoleAttributes` * * @tparam MessageT Message Type * @param role_attr instance of `RoleAttributes`, * includes channel name, qos, etc. * @param reader_func invoked when message receive * @return std::shared_ptr<cyber::Reader<MessageT>> result Reader Object */ template <typename MessageT> auto CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; /** * @brief Create a Service object with specific `service_name` * * @tparam Request Message Type of the Request * @tparam Response Message Type of the Response * @param service_name specific service name to a serve * @param service_callback invoked when a service is called * @return std::shared_ptr<Service<Request, Response>> result `Service` */ template <typename Request, typename Response> auto CreateService(const std::string& service_name, const typename Service<Request, Response>::ServiceCallback& service_callback) -> std::shared_ptr<Service<Request, Response>>; /** * @brief Create a Client object to request Service with `service_name` * * @tparam Request Message Type of the Request * @tparam Response Message Type of the Response * @param service_name specific service name to a Service * @return std::shared_ptr<Client<Request, Response>> result `Client` */ template <typename Request, typename Response> auto CreateClient(const std::string& service_name) -> std::shared_ptr<Client<Request, Response>>; bool DeleteReader(const std::string& channel_name); bool DeleteReader(const ReaderConfig& config); bool DeleteReader(const proto::RoleAttributes& role_attr); /** * @brief Observe all readers' data */ void Observe(); /** * @brief clear all readers' data */ void ClearData(); /** * @brief Get the Reader object that subscribe `channel_name` * * @tparam MessageT Message Type * @param channel_name channel name * @return std::shared_ptr<Reader<MessageT>> result reader */ template <typename MessageT> auto GetReader(const std::string& channel_name) -> std::shared_ptr<Reader<MessageT>>; private: explicit Node(const std::string& node_name, const std::string& name_space = ""); std::string node_name_; std::string name_space_; std::mutex readers_mutex_; std::map<std::string, std::shared_ptr<ReaderBase>> readers_; std::unique_ptr<NodeChannelImpl> node_channel_impl_ = nullptr; std::unique_ptr<NodeServiceImpl> node_service_impl_ = nullptr; }; template <typename MessageT> auto Node::CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>> { return node_channel_impl_->template CreateWriter<MessageT>(role_attr); } template <typename MessageT> auto Node::CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>> { return node_channel_impl_->template CreateWriter<MessageT>(channel_name); } template <typename MessageT> auto Node::CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>> { std::lock_guard<std::mutex> lg(readers_mutex_); if (readers_.find(role_attr.channel_name()) != readers_.end()) { AWARN << "Failed to create reader: reader with the same channel already " "exists."; return nullptr; } auto reader = node_channel_impl_->template CreateReader<MessageT>( role_attr, reader_func); if (reader != nullptr) { readers_.emplace(std::make_pair(role_attr.channel_name(), reader)); } return reader; } template <typename MessageT> auto Node::CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<cyber::Reader<MessageT>> { std::lock_guard<std::mutex> lg(readers_mutex_); if (readers_.find(config.channel_name) != readers_.end()) { AWARN << "Failed to create reader: reader with the same channel already " "exists."; return nullptr; } auto reader = node_channel_impl_->template CreateReader<MessageT>(config, reader_func); if (reader != nullptr) { readers_.emplace(std::make_pair(config.channel_name, reader)); } return reader; } template <typename MessageT> auto Node::CreateReader(const std::string& channel_name, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<Reader<MessageT>> { std::lock_guard<std::mutex> lg(readers_mutex_); if (readers_.find(channel_name) != readers_.end()) { AWARN << "Failed to create reader: reader with the same channel already " "exists."; return nullptr; } auto reader = node_channel_impl_->template CreateReader<MessageT>( channel_name, reader_func); if (reader != nullptr) { readers_.emplace(std::make_pair(channel_name, reader)); } return reader; } template <typename Request, typename Response> auto Node::CreateService( const std::string& service_name, const typename Service<Request, Response>::ServiceCallback& service_callback) -> std::shared_ptr<Service<Request, Response>> { return node_service_impl_->template CreateService<Request, Response>( service_name, service_callback); } template <typename Request, typename Response> auto Node::CreateClient(const std::string& service_name) -> std::shared_ptr<Client<Request, Response>> { return node_service_impl_->template CreateClient<Request, Response>( service_name); } template <typename MessageT> auto Node::GetReader(const std::string& name) -> std::shared_ptr<Reader<MessageT>> { std::lock_guard<std::mutex> lg(readers_mutex_); auto it = readers_.find(name); if (it != readers_.end()) { return std::dynamic_pointer_cast<Reader<MessageT>>(it->second); } return nullptr; } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_NODE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/writer_reader_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #include <memory> #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/common/global_data.h" #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/node/reader.h" #include "cyber/node/writer.h" namespace apollo { namespace cyber { TEST(WriterReaderTest, constructor) { const std::string channel_name("constructor"); proto::RoleAttributes attr; attr.set_channel_name(channel_name); Writer<proto::UnitTest> writer_a(attr); EXPECT_FALSE(writer_a.IsInit()); EXPECT_EQ(writer_a.GetChannelName(), channel_name); Reader<proto::UnitTest> reader_a(attr); EXPECT_FALSE(reader_a.IsInit()); EXPECT_EQ(reader_a.GetChannelName(), channel_name); attr.set_host_name("caros"); Writer<proto::UnitTest> writer_b(attr); EXPECT_FALSE(writer_b.IsInit()); EXPECT_EQ(writer_b.GetChannelName(), channel_name); Reader<proto::UnitTest> reader_b(attr); EXPECT_FALSE(reader_b.IsInit()); EXPECT_EQ(reader_b.GetChannelName(), channel_name); attr.set_process_id(12345); Writer<proto::UnitTest> writer_c(attr); EXPECT_FALSE(writer_c.IsInit()); EXPECT_EQ(writer_c.GetChannelName(), channel_name); Reader<proto::UnitTest> reader_c(attr); EXPECT_FALSE(reader_c.IsInit()); EXPECT_EQ(reader_c.GetChannelName(), channel_name); } TEST(WriterReaderTest, init_and_shutdown) { const std::string channel_name_a("init"); const std::string channel_name_b("shutdown"); proto::RoleAttributes attr; attr.set_channel_name(channel_name_a); attr.set_host_name("caros"); attr.set_process_id(12345); Writer<proto::UnitTest> writer_a(attr); EXPECT_TRUE(writer_a.Init()); EXPECT_TRUE(writer_a.IsInit()); // repeated call EXPECT_TRUE(writer_a.Init()); attr.set_channel_name(channel_name_b); attr.set_process_id(54321); Reader<proto::UnitTest> reader_a(attr); EXPECT_TRUE(reader_a.Init()); EXPECT_TRUE(reader_a.IsInit()); // repeated call EXPECT_TRUE(reader_a.Init()); Writer<proto::UnitTest> writer_b(attr); EXPECT_TRUE(writer_b.Init()); EXPECT_TRUE(writer_b.IsInit()); attr.set_channel_name(channel_name_a); attr.set_host_name("sorac"); attr.set_process_id(12345); Reader<proto::UnitTest> reader_b(attr); EXPECT_TRUE(reader_b.Init()); EXPECT_TRUE(reader_b.IsInit()); Reader<proto::UnitTest> reader_c(attr); EXPECT_FALSE(reader_c.Init()); EXPECT_FALSE(reader_c.IsInit()); writer_a.Shutdown(); // repeated call writer_a.Shutdown(); reader_a.Shutdown(); // repeated call reader_a.Shutdown(); writer_b.Shutdown(); reader_b.Shutdown(); reader_c.Shutdown(); EXPECT_FALSE(writer_a.IsInit()); EXPECT_FALSE(writer_b.IsInit()); EXPECT_FALSE(reader_a.IsInit()); EXPECT_FALSE(reader_b.IsInit()); EXPECT_FALSE(reader_c.IsInit()); } TEST(WriterReaderTest, messaging) { proto::RoleAttributes attr; attr.set_node_name("writer"); attr.set_channel_name("messaging"); auto channel_id = common::GlobalData::RegisterChannel(attr.channel_name()); attr.set_channel_id(channel_id); Writer<proto::UnitTest> writer(attr); EXPECT_TRUE(writer.Init()); std::mutex mtx; std::vector<proto::UnitTest> recv_msgs; attr.set_node_name("reader_a"); Reader<proto::UnitTest> reader_a( attr, [&](const std::shared_ptr<proto::UnitTest>& msg) { std::lock_guard<std::mutex> lck(mtx); recv_msgs.emplace_back(*msg); }); EXPECT_TRUE(reader_a.Init()); attr.set_node_name("reader_b"); Reader<proto::UnitTest> reader_b( attr, [&](const std::shared_ptr<proto::UnitTest>& msg) { std::lock_guard<std::mutex> lck(mtx); recv_msgs.emplace_back(*msg); }); EXPECT_TRUE(reader_b.Init()); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name("WriterReaderTest"); msg->set_case_name("messaging"); writer.Write(msg); std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(500)); EXPECT_EQ(recv_msgs.size(), 2); EXPECT_TRUE(writer.HasReader()); EXPECT_TRUE(reader_a.HasWriter()); writer.Shutdown(); reader_a.Shutdown(); reader_b.Shutdown(); } TEST(WriterReaderTest, observe) { proto::RoleAttributes attr; attr.set_node_name("node"); attr.set_channel_name("channel"); auto channel_id = common::GlobalData::RegisterChannel(attr.channel_name()); attr.set_channel_id(channel_id); attr.mutable_qos_profile()->set_depth(10); Reader<proto::UnitTest> reader(attr); reader.Init(); EXPECT_TRUE(reader.Empty()); EXPECT_FALSE(reader.HasReceived()); auto latest = reader.GetLatestObserved(); auto oldest = reader.GetOldestObserved(); EXPECT_EQ(latest, nullptr); EXPECT_EQ(oldest, nullptr); auto msg1 = std::make_shared<proto::UnitTest>(); msg1->set_case_name("message_1"); reader.Enqueue(msg1); EXPECT_TRUE(reader.HasReceived()); auto msg2 = std::make_shared<proto::UnitTest>(); msg2->set_case_name("message_2"); reader.Enqueue(msg2); reader.Observe(); EXPECT_FALSE(reader.Empty()); latest = reader.GetLatestObserved(); oldest = reader.GetOldestObserved(); ASSERT_NE(latest, nullptr); EXPECT_EQ(latest->case_name(), "message_2"); ASSERT_NE(oldest, nullptr); EXPECT_EQ(oldest->case_name(), "message_1"); auto msg3 = std::make_shared<proto::UnitTest>(); msg3->set_case_name("message_3"); for (int i = 0; i < 5; ++i) { reader.Enqueue(msg3); } reader.Observe(); oldest = reader.GetOldestObserved(); EXPECT_EQ(oldest->case_name(), "message_1"); reader.SetHistoryDepth(5); reader.Observe(); oldest = reader.GetOldestObserved(); EXPECT_EQ(oldest->case_name(), "message_3"); for (auto it = reader.Begin(); it != reader.End(); ++it) { EXPECT_EQ((*it)->case_name(), "message_3"); } reader.ClearData(); EXPECT_TRUE(reader.Empty()); EXPECT_FALSE(reader.HasReceived()); Writer<proto::UnitTest> writer(attr); writer.Init(); writer.Write(msg1); std::this_thread::sleep_for(std::chrono::milliseconds(10)); ASSERT_TRUE(reader.HasReceived()); reader.Observe(); ASSERT_FALSE(reader.Empty()); latest = reader.GetLatestObserved(); EXPECT_EQ(latest->case_name(), "message_1"); } TEST(WriterReaderTest, get_delay_sec) { proto::RoleAttributes attr; attr.set_node_name("node"); attr.set_channel_name("channel"); auto channel_id = common::GlobalData::RegisterChannel(attr.channel_name()); attr.set_channel_id(channel_id); Reader<proto::UnitTest> reader(attr); reader.Init(); EXPECT_LT(reader.GetDelaySec(), 0); reader.Enqueue(std::make_shared<proto::UnitTest>()); EXPECT_GT(reader.GetDelaySec(), 0); sleep(1); reader.Enqueue(std::make_shared<proto::UnitTest>()); EXPECT_GT(reader.GetDelaySec(), 1); } class Message { public: uint64_t timestamp; std::string content; // void GetDescriptorString(const std::string& type, std::string* desc_str) {} }; TEST(WriterReaderTest, user_defined_message) { proto::RoleAttributes attr; attr.set_channel_name("/internal_channel"); auto channel_id = common::GlobalData::RegisterChannel(attr.channel_name()); attr.set_channel_id(channel_id); attr.mutable_qos_profile()->set_depth(10); EXPECT_FALSE(message::HasSerializer<Message>::value); EXPECT_FALSE(message::HasType<Message>::value); auto node = CreateNode("node"); ASSERT_TRUE(node); auto writer = node->CreateWriter<Message>(attr); auto reader = node->CreateReader<Message>(attr); auto msg = std::make_shared<Message>(); msg->timestamp = 100; msg->content = "message"; writer->Write(msg); std::this_thread::sleep_for(std::chrono::milliseconds(10)); writer->Write(msg); std::this_thread::sleep_for(std::chrono::milliseconds(10)); writer->Write(msg); std::this_thread::sleep_for(std::chrono::milliseconds(10)); reader->Observe(); ASSERT_TRUE(reader->HasReceived()); ASSERT_FALSE(reader->Empty()); auto latest = reader->GetLatestObserved(); EXPECT_EQ(latest->timestamp, 100); EXPECT_EQ(latest->content, "message"); } } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/writer_base.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_WRITER_BASE_H_ #define CYBER_NODE_WRITER_BASE_H_ #include <atomic> #include <mutex> #include <string> #include <vector> #include "cyber/proto/role_attributes.pb.h" namespace apollo { namespace cyber { /** * @class WriterBase * @brief Base class for a Writer. A Writer is an object to send messages * through a 'Channel' * @warning One Writer can only write one channel. * But different writers can write through the same channel */ class WriterBase { public: /** * @brief Construct a new Writer Base object * * @param role_attr role attributes for this Writer */ explicit WriterBase(const proto::RoleAttributes& role_attr) : role_attr_(role_attr), init_(false) {} virtual ~WriterBase() {} /** * @brief Init the Writer * * @return true if init success * @return false if init failed */ virtual bool Init() = 0; /** * @brief Shutdown the Writer */ virtual void Shutdown() = 0; /** * @brief Is there any Reader that subscribes our Channel? * You can publish message when this return true * * @return true if the channel has reader * @return false if the channel has no reader */ virtual bool HasReader() { return false; } /** * @brief Get all Readers that subscriber our writing channel * * @param readers result vector of RoleAttributes */ virtual void GetReaders(std::vector<proto::RoleAttributes>* readers) {} /** * @brief Get Writer's Channel name * * @return const std::string& const reference to the channel name */ const std::string& GetChannelName() const { return role_attr_.channel_name(); } /** * @brief Is Writer initialized? * * @return true if the Writer is inited * @return false if the Write is not inited */ bool IsInit() const { std::lock_guard<std::mutex> g(lock_); return init_; } protected: proto::RoleAttributes role_attr_; mutable std::mutex lock_; bool init_; }; } // namespace cyber } // namespace apollo #endif // CYBER_NODE_WRITER_BASE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/node/writer.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed 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. *****************************************************************************/ #ifndef CYBER_NODE_WRITER_H_ #define CYBER_NODE_WRITER_H_ #include <memory> #include <string> #include <vector> #include "cyber/proto/topology_change.pb.h" #include "cyber/common/log.h" #include "cyber/node/writer_base.h" #include "cyber/service_discovery/topology_manager.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { /** * @class Writer<MessageT> * @brief The Channel Writer has only one function: publish message through the * channel pointed in its RoleAttributes * * @tparam MessageT Message Type of the Writer handles */ template <typename MessageT> class Writer : public WriterBase { public: using TransmitterPtr = std::shared_ptr<transport::Transmitter<MessageT>>; using ChangeConnection = typename service_discovery::Manager::ChangeConnection; /** * @brief Construct a new Writer object * * @param role_attr we use RoleAttributes to identify a Writer */ explicit Writer(const proto::RoleAttributes& role_attr); virtual ~Writer(); /** * @brief Init the Writer * * @return true if init successfully * @return false if init failed */ bool Init() override; /** * @brief Shutdown the Writer */ void Shutdown() override; /** * @brief Write a MessageT instance * * @param msg the message we want to write * @return true if write successfully * @return false if write failed */ virtual bool Write(const MessageT& msg); /** * @brief Write a shared ptr of MessageT * * @param msg_ptr the message shared ptr we want to write * @return true if write successfully * @return false if write failed */ virtual bool Write(const std::shared_ptr<MessageT>& msg_ptr); /** * @brief Is there any Reader that subscribes our Channel? * You can publish message when this return true * * @return true if the channel has reader * @return false if the channel has no reader */ bool HasReader() override; /** * @brief Get all Readers that subscriber our writing channel * * @param readers vector result of RoleAttributes */ void GetReaders(std::vector<proto::RoleAttributes>* readers) override; private: void JoinTheTopology(); void LeaveTheTopology(); void OnChannelChange(const proto::ChangeMsg& change_msg); TransmitterPtr transmitter_; ChangeConnection change_conn_; service_discovery::ChannelManagerPtr channel_manager_; }; template <typename MessageT> Writer<MessageT>::Writer(const proto::RoleAttributes& role_attr) : WriterBase(role_attr), transmitter_(nullptr), channel_manager_(nullptr) {} template <typename MessageT> Writer<MessageT>::~Writer() { Shutdown(); } template <typename MessageT> bool Writer<MessageT>::Init() { { std::lock_guard<std::mutex> g(lock_); if (init_) { return true; } transmitter_ = transport::Transport::Instance()->CreateTransmitter<MessageT>( role_attr_); if (transmitter_ == nullptr) { return false; } init_ = true; } this->role_attr_.set_id(transmitter_->id().HashValue()); channel_manager_ = service_discovery::TopologyManager::Instance()->channel_manager(); JoinTheTopology(); return true; } template <typename MessageT> void Writer<MessageT>::Shutdown() { { std::lock_guard<std::mutex> g(lock_); if (!init_) { return; } init_ = false; } LeaveTheTopology(); transmitter_ = nullptr; channel_manager_ = nullptr; } template <typename MessageT> bool Writer<MessageT>::Write(const MessageT& msg) { RETURN_VAL_IF(!WriterBase::IsInit(), false); auto msg_ptr = std::make_shared<MessageT>(msg); return Write(msg_ptr); } template <typename MessageT> bool Writer<MessageT>::Write(const std::shared_ptr<MessageT>& msg_ptr) { RETURN_VAL_IF(!WriterBase::IsInit(), false); return transmitter_->Transmit(msg_ptr); } template <typename MessageT> void Writer<MessageT>::JoinTheTopology() { // add listener change_conn_ = channel_manager_->AddChangeListener(std::bind( &Writer<MessageT>::OnChannelChange, this, std::placeholders::_1)); // get peer readers const std::string& channel_name = this->role_attr_.channel_name(); std::vector<proto::RoleAttributes> readers; channel_manager_->GetReadersOfChannel(channel_name, &readers); for (auto& reader : readers) { transmitter_->Enable(reader); } channel_manager_->Join(this->role_attr_, proto::RoleType::ROLE_WRITER, message::HasSerializer<MessageT>::value); } template <typename MessageT> void Writer<MessageT>::LeaveTheTopology() { channel_manager_->RemoveChangeListener(change_conn_); channel_manager_->Leave(this->role_attr_, proto::RoleType::ROLE_WRITER); } template <typename MessageT> void Writer<MessageT>::OnChannelChange(const proto::ChangeMsg& change_msg) { if (change_msg.role_type() != proto::RoleType::ROLE_READER) { return; } auto& reader_attr = change_msg.role_attr(); if (reader_attr.channel_name() != this->role_attr_.channel_name()) { return; } auto operate_type = change_msg.operate_type(); if (operate_type == proto::OperateType::OPT_JOIN) { transmitter_->Enable(reader_attr); } else { transmitter_->Disable(reader_attr); } } template <typename MessageT> bool Writer<MessageT>::HasReader() { RETURN_VAL_IF(!WriterBase::IsInit(), false); return channel_manager_->HasReader(role_attr_.channel_name()); } template <typename MessageT> void Writer<MessageT>::GetReaders(std::vector<proto::RoleAttributes>* readers) { if (readers == nullptr) { return; } if (!WriterBase::IsInit()) { return; } channel_manager_->GetReadersOfChannel(role_attr_.channel_name(), readers); } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_WRITER_H_
0