server action что это
Actions
Actions are one of the three core types of interaction between ROS nodes. This article specifies the requirements for actions, how they’ve changed from ROS 1, and how they’re communicated.
Date Written: 2019-03
Last Modified: 2020-05
Background
There are three forms of communication in ROS: topics, services, and actions. Topic publishers broadcast to multiple subscribers, but communication is one-way. Service clients send a request to a service server and get a response, but there is no information about the progress. Similar to services, action clients send a request to an action server in order to achieve some goal and will get a result. Unlike services, while the action is being peformed an action server sends progress feedback to the client.
Actions are useful when a response may take a significant length of time. They allow a client to track the progress of a request, get the final outcome, and optionally cancel the request before it completes.
This document defines requirements for actions, how they are specified in the ROS Message IDL, and how they are communicated by the middleware.
Entities Involved in Actions
There are two entities involved in actions: an action server and an action client.
Action Server
An action server provides an action. Like topics and services, an action server has a name and a type. The name is allowed to be namespaced and must be unique across action servers. This means there may be multiple action servers that have the same type running simultaneously (under different namespaces).
It is responsible for:
Action Client
An action client sends one or more goals (an action to be performed) and monitors their progress. There may be multiple clients per server; however, it is up to the server to decide how goals from multiple clients will be handled simultaneously.
It is responsible for:
Differences between ROS 1 and ROS 2 actions
First Class Support
In ROS 2, actions will be included in the client library implementations. The work of writing a client library in a new language will be reduced by creating a common implementation in C.
Services used for Actions
In ROS 1, actions were implemented using a set of topics under a namespace taken from the action name. ROS 1 services were not used because they are inherently synchronous and actions need to be asynchronous. Actions also needed to send status/feedback and be cancelable.
In ROS 2, services are asynchronous in the common C implementation, so actions will use a combination of services and topics.
Goal Identifiers
In ROS 1, an action client can create a goal ID when submitting a goal. This potentially leads to scenarios where mutliple clients independently generate the same goal ID. If an empty goal ID is sent, the action server will create one instead, which is not very useful since the client has no way to know the goal ID.
In ROS 2, action clients will be the sole entities responsible for generating the goal ID. This way clients always know the goal ID for an action. Futhermore, a UUID will be used for each goal to mitigate the issue of goal ID collision across multiple clients.
Namespacing of Generated Messages and Services
Visibility of Action Services and Topics
In ROS 1, rostopic list would show all action topics in its output. In ROS 2, ros2 topic list and ros2 service list will not show topics and services used by actions by default. They can still be shown by passing an option to the commands to show hidden services and topics. The tool ros2 action list will produce list of action names provided by action servers (see Introspection tools).
Action Interface Definition
Actions are specified using a form of the ROS Message IDL. The specification contains three sections, each of which is a message specification:
This describes what the action should achieve and how it should do it. It is sent to the action server when it is requested to execute an action.
This describes the outcome of an action. It is sent from the server to the client when the action execution ends, whether successfully or not.
This describes the progress towards completing an action. It is sent to the client of the action from the action server between commencing action execution and prior to the action completing. This data is used by the client to understand the progress of executing the action.
Example
Introspection tools
Actions, like topics and services, are introspectable from the command line.
Each action will be listed and treated as a single unit by this tool.
Goal States
The action server maintains a state machine for each goal it accepts from a client. Rejected goals are not part of the state machine.
There are three active states:
And three terminal states:
State transitions triggered by the action server according to its designed behavior:
State transitions triggered by the action client:
Usage examples can be found in the examples repository.
Middleware implementation
Under the hood, an action is made up of three services and two topics. In this section, they are descibed in detail.
Send Goal Service
The purpose of this service is to send a goal to the action server. It is the first service called to begin an action, and is expected to return quickly. The description of the goal in the request is user-defined as part of the Action Interface Definition.
The QoS settings of this service should be set so the client is guaranteed to receive a response or an action could be executed without a client being aware of it.
Cancel Goal Service
The cancel request policy is the same as in ROS 1.
Get Result Service
The purpose of this service is to get the final result of a goal. After a goal has been accepted the client should call this service to receive the result. The result will indicate the final status of the goal and any user defined data as part of the Action Interface Definition.
Result caching
The server should cache the result once it is ready so multiple clients have to opportunity to get it. This is also useful for debugging/introspection tools.
To free up resources, the server should discard the result after a configurable timeout period. The timeout can be set as part of options to the action server. If the timeout is configured to have value -1, then goal results will be “kept forever” (until the action server shuts down). If the timeout is configured to have value 0, then goal results are discarded immediately (after responding to any pending result requests).
Goal Status Topic
This topic is published by the server to broadcast the status of goals it has accepted. The purpose of the topic is for introspection; it is not used by the action client. Messages are published when transitions from one status to another occur.
The QoS settings for an action server can be configured by the user. The default QoS settings for a DDS middleware should be TRANSIENT LOCAL with a history size of 1. This allows new subscribers to always get the latest state.
The possible statuses are:
Feedback Topic
This topic is published by the server to send progress feedback about the goal that is user-defined as part of the Action Interface Definition. It is up to the author of the action server to decide how often to publish the feedback.
The QoS settings for feedback coming from an action server can be configured by the user. It is up to the clients to use compatible QoS settings.
Client/Server Interaction Examples
Here are a couple of sequence diagrams depicting typical interactions between an action client and action server.
Example 1
In this example, the action client requests a goal and gets a response from the server accepting the goal (synchronous). Upon accepting the goal, the action server starts a user defined execution method for completing the goal. Following the goal request, the client makes an asynchronous request for the result. The user defined method publishes feedback to the action client as it executes the goal. Ultimately, the user defined method populates a result message that is used as part of the result response.
Example 2
This example is almost identical to the first, but this time the action client requests for the goal to be canceled mid-execution. Note that the user defined method is allowed to perform any shutdown operations after the cancel request before returning with the cancellation result.
Example 3
Here is a more complex example involving multiple goals.
Topic and Service Name Examples
Example: fully qualified action name
Example: relative action name
Example: private action name
Bridging between ROS 1 and ROS 2
Alternatives
These alternative approaches to actions in ROS 2 were considered.
Actions in rmw
An alternative to using services and topics is to implement actions in the rmw layer. This would enable using middleware specific features better suited to actions. The default middleware in ROS 2 uses DDS, and there don’t appear to be any DDS features better for actions than what are used for services and topics. Additionally implementing actions in the rmw implementations increases the complexity of writing an rmw implementation. For these reasons actions will be implemented at a higher level.
Multiple topics for feedback and status
When there are many goals from many clients, the choice to have a single feedback (and status) topic per action server is suboptimal in terms of processing and bandwidth resource. It is up to clients to filter out feedback/status messages that are not pertinent to them. In this scenario, M goals are sent to N clients there is an unecessary use of bandwidth and processing; especially in extreme cases where M and N are large.
One approach is to use multiple topics (distinguished by goal IDs) or the “keyed data” feature in DDS that allows for “content filtered subscription”. This would allow clients to only subscribe to the feedback and status messages that they care about.
A second approach is to give clients the option to specify a custom feedback topic as part of the goal request. This would be useful to alleviate extreme cases without the overhead of creating/destroying topics for every goal when the number of goals/clients is small.
Reasons against using separate topics for feedback and status:
It seems reasonable in the future that the “keyed data” feature in DDS can be employed to reduce overhead in the “many goal/client” scenario. This will require that the feature be exposed in the middleware, which it is not at the time of writing this proposal.
Server-side goal ID generation
Since new goals are created by an action client making a service call to an action server, it is possible for the action server to generate the UUID for the goal and return it as part of the service response to the action client. The action server can better ensure uniqueness of the goal ID with this approach, but should still handle the potential race of two goal requests arriving simulataneously.
On the other hand, it would be nice to expose the method for generating goal IDs and let the user correlate the goals with other libraries/systems. Imagine an action client being used to request a robot to perform tasks from a database where each task already has a UUID associated with it. In this case, it is still the action servers responsibility to ensure goal ID uniqueness and handle any potential races with concurrent goal requests, but we have the added benefit of the user being able to correlate goals to other existing entities.
Работа с Action
Модель коммуникации в режиме Действие (Action) используется, когда выполнение запрошенной команды занимает продолжительное время и необходима обратная связь с процессом. Это очень похоже на модель Service: (Service Request) используется как Задача (Action Goal), а ответ (Service Response) используется как Результат (Action Result). Также есть дополнительная сущность Обратная Связь (Action Feedback) для передачи промежуточных результатов выполнения процесса для клиента.
В отличие от службы (Service), действие (Action) часто используется для управления сложными задачами робота, такими как передвижение к заданной точке, запуск лазерного сканирования, перемещение манипуляторов робота по сложной траектории и т.п.
Для файла DoDishes.action будут созданы файлы
Дополнительная информация о работе с Действиями (Action) доступна на станице ROS wiki http://wiki.ros.org/actionlib
Примеры работы на Python
Action Server
Сервер получает задачу от клиента с параметрами, запускает процесс выполнения и информирует клиента об промежуточных результатах. После выполнения задачи, сервер сообщает клиенту об успешном завершении.
Для действия описанного в файле DoDishes.action пакета ros_book_samples напишем пример сервера action_server.py
Action Client
Клиент создает задачу на сервере, обрабатывает обратную связь и выводит финальный результат.
Запуск примеров возможен или через прямой запуск скриптов python или через запуск rosrun
При правильной работе Клиента и Сервера, в консоли, с задержкой в 1 секунду, выведется количество вымытых тарелок и финальный результат.
Использование модели Action в новых пакетах
В файле CMakeLists.txt необходимо внести изменения
В файле package.xml должны быть подключенны зависимости
Дополнительная информация
Модуль ActionLib имеет довольно сложную структуру взаимодействия и выполнения задач. Как Сервер так и Клиент обрабатывают запросы по принципу Машины состояния (State Machine). Задачи могут отменяться, останавливаться и заново запускаться. Подробное описание этого взаимодействия описано на Wiki странице http://wiki.ros.org/actionlib/DetailedDescription
Не так важно сейчас в этом полностью разобраться, как важно знать, что эти механизмы существуют и обратиться к документации, когда это будет необходимо.
GitHub Actions: Простой способ развернуть множество стендов фронтенд-приложения
Деплоим с поддержкой ветвления без навыков DevOps на примере Vue
Грубо говоря, GitHub Actions – это написанные пользователем сценарии, выполнение которых можно затриггерить по определенным действиям в репозитории (например, новый коммит).
Можно выделить следующие преимущества GitHub Actions среди других CI инструментов:
В статье описана реализация следующего сценария, который поможет упростить тестирование и разработку вашего приложения:
Все действия будут выполнены на OC Ubuntu 20.04. Также нам понадобится доступ к NS-записям домена.
Подойдет cамая минимальная конфигурация, достаточная для раздачи статики. Остальную работу на себя возьмут серверы Гитхаба.
P.S.: Читателям статьи VScale предоставили купон VCGUIDE на 250 рублей.
Авторизуемся сгенерированным паролем с помощью командной строки или любого SSH клиента:
Установим nginx – он будет отвечать за раздачу файлов приложения:
Далее создадим SSH-ключ, который понадобится нам для деплоя приложения на сервер:
Нам будет предложено задать секретный пароль, пропустим этот шаг (Enter).
Добавим ключ в доверенные:
И перезапустим сервис sshd для применения изменений:
Подходит для хранения приватной информации – например, нашего SSH-ключа. Значения этих переменных будут скрыты из вывода в консоль и будут доступны только нам.
Задаем следующие переменные в настройках:
Создадим в нашем репозитории шаблон для задачи, отвечающей за деплой:
В примере выше используется созданный пользователем пакет appleboy/scp-action, выполняющий функцию архивирования файлов, передачу созданного архива по SSH и его распаковку на удаленном сервере.
Для начала нужно привязать имеющийся домен к серверу.
В панеле управления доменом зададим DNS-серверы/NS-записи ns1.vscale.io и ns2.vscale.io
В настройках домена добавим новую запись *.example.ru, указывающую на IP нашего сервера:
Установим клиент ACME.sh для работы с Let’s Encrypt:
Для получения и продления wildcard-сертификатов нужно добавлять специальную текстовую запись для домена. Создадим API токен с полными правами, чтобы не делать это каждый раз вручную.
Добавим полученный токен в переменные окружения сервера:
Следующая команда инициирует создание сертификатов для доменов *.example.ru и *.app.example.ru соответственно:
Ждем окончания проверки, в случае успеха получаем такое сообщение:
При каждом коммите в ветку, GitHub Action собирает приложение и отправляет его в директорию /var/www/app/
/ у нас на сервере.
Нужно настроить сервер так, чтобы запросы к поддомену
.app.example.ru указывали на соответствующую директорию.
Создадим/заменим стандартную конфигурацию nginx (/etc/nginx/sites-available/default):
С помощью регулярного выражения проверяется директива server_name: при соответствии правилу, значение поддомена подставляется в качестве имени root-директории, в которой находится уже собранное приложение.
Для применения изменений перезагружаем nginx:
Страница
Пользователь
Note: This tutorial assumes that you have completed the previous tutorials: ROS tutorials. |
|
Writing a Simple Action Server using the Execute Callback
Description: This tutorial covers using the simple_action_server library to create a Fibonacci action server. This example action server generates a Fibonacci sequence, the goal is the order of the sequence, the feedback is the sequence as it is computed, and the result is the final sequence.
Tutorial Level: BEGINNER
Creating the Action Messages
Before writing an action it is important to define the goal, result, and feedback messages. The action messages are generated automatically from the .action file, for more information on action files see the actionlib documentation. This file defines the type and format of the goal, result, and feedback topics for the action. Create actionlib_tutorials/action/Fibonacci.action in your favorite editor, and place the following inside it:
To automatically generate the message files during the make process, a few things need to be added to CMakeLists.txt.
add the actionlib_msgs package to the find_package macro’s argument like this (if you used catkin_create_package to generate CMakeLists.txt, this may already have been added):
Note that CMake needs to find_package actionlib_msgs ( message_generation does not need to be listed explicitly, it is referenced implicitly by actionlib_msgs).
use the add_action_files macro to declare the actions you want to be generated:
call the generate_messages macro, not forgetting the dependencies on actionlib_msgs and other message packages like std_msgs:
add actionlib_msgs to catkin_package macro like this:
catkin_package also specifies only CATKIN_DEPEND to actionlib_msgs. The transitive dependency on message_runtime is happening automatically.
Note: Sometimes you have to setup your package.xml, since we are generating messages you have to declare on the manifest file that at run time you have to generate messages. You could just insert the follow line.
Now by following, automatically generate msg files of your action files, and also see the result.
To automatically generate the message files during the make process, add the following to CMakeLists.txt (before the rosbuild_init call)
You’ll also need to make sure to generate header files from the message files generated by the genaction.py script. To do this, uncomment the following line at the bottom your CMakeLists.txt file if you have not already.
To manually generate the message files from this file, use the script genaction.py from the actionlib_msgs package.
Writing a Simple Server
The Code
First, create actionlib_tutorials/src/fibonacci_server.cpp in your favorite editor, and place the following inside it:
The Code Explained
Now, let’s break down the code piece by piece.
actionlib/server/simple_action_server.h is the action library used from implementing simple actions.
This includes the action message generated from the Fibonacci.action file show above. This is a header generated automatically from the FibonacciAction.msg file. For more information on message definitions, see the msg page.
These are the protected variables of the action class. The node handle is constructed and passed into the action server during construction of the action. The action server is constructed in the constructor of the action and has been discussed below. The feedback and result messages are created for publishing in the action.
In the action constructor, an action server is created. The action server takes arguments of a node handle, name of the action, and optionally an executeCB. In this example the action server is created with the arguments for the executeCB.
Now the executeCB function referenced in the constructor is created. The callback function is passed a pointer to the goal message. Note: This is a boost shared pointer, given by appending «ConstPtr» to the end of the goal message type.
Here the internals of the action are created. In this example ROS_INFO is being published to let the user know that the action is executing.
An important component of an action server is the ability to allow an action client to request that the current goal execution be cancelled. When a client requests that the current goal be preempted the action server should cancel the goal, perform necessary clean-up, and call the function setPreempted(), which signals that the action has been preempted by user request. Setting the rate at which the action server checks for preemption requests is left to the implementor of the server.
Here the Fibonacci sequence is put into the feedback variable and then published on the feedback channel provided by the action server. Then the action continues on looping and publishing feedback.
Once the action has finished computing the Fibonacci sequence the action notifies the action client that the action is complete by setting succeeded.
Finally the main function, creates the action and spins the node. The action will be running and waiting to receive goals.
Compiling
Add the following lines to your CMakeLists.txt file:
The minimal entire CMakeLists.txt would look like this:
In ROS fuerte, use the boost linking macros around rosbuild_add_executable:
Then build as usual.
Running the Action server
Start a roscore in a new terminal
And then run the action server:
You will see something similar to:
To check that your action is running properly list topics being published:
You will see something similar to:
Alternatively you can look at the nodes:
This shows that your action server is publishing the feedback, status, and result channels as expected and subscribed to the goal and cancel channels as expected. The action server is up and running properly.
Sending a Goal to the Action Server
For the next step in using your action, you need to Ctrl-C the action server and write a simple action client.
Wiki: actionlib_tutorials/Tutorials/SimpleActionServer(ExecuteCallbackMethod) (последним исправлял пользователь ChrisLalancette 2018-05-21 18:37:36)