Дерево страниц

Сравнение версий

Ключ

  • Эта строка добавлена.
  • Эта строка удалена.
  • Изменено форматирование.
Комментарий: Published by Scroll Versions from space TMAG and version 7.14
Sv translation
languageru


Примеры представляют собой исходные коды консольных утилит, которые реализуют загрузку событий в Traffic Monitor, используя Thrift-интерфейс PushAPI SDK.

Консольные утилиты

  • утилита pushapi-cpp реализована на языке С++. Подготовлена к сборке в операционных системах Windows и Linux. Данная утилита демонстрирует сценарии загрузки всех типов событий, которые уже зарегистрированы в системе Traffic Monitor.
  • утилита pushapi-csharp реализована на языке С#. Подготовлена к сборке в операционной системе Windows. Данная утилита демонстрирует сценарии загрузки всех типов событий, которые уже зарегистрированы в системе Traffic Monitor.
  • утилита pushapi-demo.py реализована на языке Python. Подготовлена к сборке в операционных системах Windows и Linux. Демонстрирует сценарии загрузки всех типов событий, которые уже зарегистрированы в системе Traffic Monitor.
  • утилита pushapi-util реализована на языке С++. Подготовлена к сборке в операционных системах Windows и Linux. Данная утилита имеет Имеет развитый интерфейс командной строки, который позволяет загружать произвольные события в систему Traffic Monitor, в том числе те, которые зарегистрированы внешней системой.

Описание командной строки утилиты pushapi-util

Блок кода
languagetext
./pushapi-util
--host <pushapi_address> [--port <pushapi_port>]
--token <plugin_token>
--id <company>
--class <event_class>
--service <event_service>
--evtattr <attr_name:attr_value,…, attr_name:attr_value>
--sender <contact_type:contact_value,attr_name:attr_value,…,attr_name:attr_value>
--receiver <contact_type:contact_value,attr_name:attr_value,…,attr_name:attr_value>
--data file:<data_falie_name>, attr_name:attr_value,…, attr_name:attr_value
--mes <contact_type:contact_value>,"message text"
[–-addctx]
[–-show_event]

Где:

  • <pushapi_address> – адрес PushAPI-сервера;
  • <pushapi_port> – порт PushAPI-сервера, если . Если не указан, используется значение по умолчанию;
  • <plugin_token> – токен авторизации плагина. Скопируйте его значение в разделе данного плагина консоли Консоли управления Traffic Monitor;
  • <company> – идентификатор компании-производителя плагина. Произвольная строка, обязательно совпадающая с той, что использовалась для генерации лицензии для плагина;
  • <event_class> – класс передаваемого события;
  • <event_service> – сервис передаваемого события. Плагин может зарегистрировать свои перехватываемые сервисы по имени и передавать их;
  • --evtattr – атрибуты передаваемого события. Посмотреть можно в списке команд с примером. Некоторые имена атрибутов имеют фиксированные значения и бизнес-смысл;
  • --sender – отправитель события. Первая пара параметров определяет контакт отправителя. Далее указываются атрибуты отправителя.

    Раскрыть
    titleСуществуют три особых типа контактов:
    • dev – отправитель/получатель является устройством;
    • res – отправитель/получатель является ресурсом;
    • ws – отправитель/получатель является Рабочей станцией.

    Если не задан ни один отправитель, то будет сгенерировано два отправителя с типом Персона и контактом типа auth; и с типом Рабочая станция и контактом dnshostname. Задан может быть только один отправитель;

    Информация
    iconfalse
    titleПример:

    Для события с отправителем с аккаунтом Вконтакте и указанием мета-информацииметаданных:

    Блок кода
    languagetext
    --sender "vkontakte:349051292:'{\"display_name\":\"some name\",\"url\":\"some_url\",\"login\":\"some_login\"}'"
  • --receiver – получатель события. Параметры аналогичны отправителю;
  • --data – данные события. Первая пара атрибутов указывает на путь к файлу, где содержится тело события. Остальные параметры описывают атрибуты этих данных. Для некоторых типов событий некоторые атрибуты обязательны;
  • --mes – передача сообщений класса Беседа. Указывается контакт отправителя сообщения и его содержимое. Сообщений может быть несколько;
  • --addctx – необязательный параметр. Автоматически добавляет к событию двух отправителей с типом Персона и контактом типа auth; и с типом Рабочая станция и контактом типа dnshostname;
  • --show_event – необязательный параметр. Выводит информацию о структуре События события (Event) в консоль в формате JSON.

Установка pushapi-util

Утилиту pushapi-util можно установить из пакета QATOOLS. Для этого:

  1. На рабочей станции с установленным Traffic Monitor извлеките pushapi-util в каталог /opt/iw/tm5/bin. Утилита pushapi-util находится в пакете iwtm-qatools-x.x.x.xxx-release.xrpm/iwtm-qatools-x.x.x.xxx-release.x86_64.cpio/./opt/iw/tm5/bin. Здесь x.x.x.xxx – это номер сборки.

    Информация
    titleПримечание:

    Если pushapi-util извлечена в другой каталог, то добавьте его в переменные окружения:

    Блок кода
    languagetext
    export PATH=$PATH:<directory>
  2. Перейдите в каталог, куда извлечена утилита pushapi-util.
  3. Сделайте файл утилиты исполняемым:

    Блок кода
    languagetext
    chmod u+x pushapi-util

Примеры вызова утилиты pushapi-util есть в исходных кодах примеров, а также приведены в статье Примеры использования утилиты pushapi-util.

Сборки примеров PushAPI SDK

Особенности сборки примеров PushAPI SDK приведены в следующих статьях:

В состав примеров SDK также входят:

  • файл plugin.json – JSON-схема файла manifest.json, который входит в состав файла регистрации внешнего плагина;
  • файл plugin.zip – пример файла регистрации внешнего плагина.

    Предупреждение
    titleВажно!

    В состав файла входит истекшая лицензия. Для регистрации плагина на основании файла примера нужно получить новую лицензию.

Sv translation
languageen

Samples are the source codes of console utilities, which implement loading events into Traffic Monitor using Thrift interface of PushAPI SDK.

Console utilities

  • The pushapi-cpp utility is implemented in С++ and prepared for assembly in Windows and Linux operating systems. This utility demonstrates scripts of loading all event types that are already registered with Traffic Monitor.
  • The pushapi-csharp utility is implemented in С# and prepared for assembly in Windows operating system. This utility demonstrates scripts of loading all event types that are already registered with Traffic Monitor.
  • The pushapi-demo.py utility is implemented in Python. It is prepared for assembly in Windows and Linux operating systems. This utility demonstrates scripts of loading all event types that are already registered with Traffic Monitor.
  • The pushapi-util utility is implemented in С++ and prepared for assembly in Windows and Linux operating systems. This utility has an advanced command-line interface that enables uploading any events to Traffic Monitor system, including events registered with an external system.

The pushapi-util utility command line description

Блок кода
languagetext
./pushevent-util 
--host <pushapi_address> [--port <pushapi_port>] 
--token <plugin_token> 
--id <company>
--class <event_class> 
--service <event_service>
--evtattr <attr_name:attr_value,…, attr_name:attr_value>
--sender <contact_type:contact_value,attr_name:attr_value,…,attr_name:attr_value>
--receiver <contact_type:contact_value,attr_name:attr_value,…,attr_name:attr_value>
--data file:<data_falie_name>, attr_name:attr_value,…, attr_name:attr_value
--mes <contact_type:contact_value>,"message text"
[–-addctx]
[–-show_event]

Where:

  • <pushapi_address > – PushAPI server address
  • <pushapi_port> – PushAPI server port. If the port is not specified, a default value is used
  • <plugin_token> – the plugin authorization token. Copy it from the section of the given plugin in the Traffic Monitor Console
  • <company> – an identifier of the plugin vendor. A string, which must be the same as the string used for generating a license for the plugin
  • <event_class> – the class of the passed event
  • <event_service> – the service of the passed event. The plugin can register intercepted services by their names and pass the names;
  • --evtattr – attributes of the passed event. Can be viewed in the list of commands with a sample. Some attribute names have fixed values and business sense
  • --sender – the event sender. The first pair of parameters defines the sender's contact. Then the sender's attributes are specified.

    Раскрыть
    titleThere are three special contact types:
    • dev – the sender/recipient is a device;
    • res – the sender/recipient is a resource;
    • ws – the sender/recipient is a "Workstation".

    If no sender is specified, then two senders will be generated: one sender with Person type and the auth contact type and the other sender with Workstation type and dnshostname contact. Only one sender can be specified

    Информация
    iconfalse
    titleExample:

    If the event sender has a VK account and meta-information is specified for the event: 

    Блок кода
    languagetext
    --sender "vkontakte:349051292:'{\"display_name\":\"some name\",\"url\":\"some_url\",\"login\":\"some_login\"}'"
  • --receiver – the event recipient. Has the same parameters as the sender
  • --data – the event data. The first pair of parameters defines the path to a file with the event body. Other parameters describe attributes of these data. For some event types, particular attributes are required
  • --mes – passing events of Chat class. A contact of the message sender and the message contents are specified. There can be several messages
  • --addctx – an optional parameter. Automatically adds two senders to the event: one sender with Person type and auth contact type and the other sender with Workstation type and dnshostname contact type;
  • --show_event – an optional parameter. Outputs information about the Event structure to the console. The information is output in JSON format.

pushapi-util utility installation

To install the pushapi-util utility from the QATOOLS package:

  1. On the workstation with Traffic Monitor installed, extract pushapi-util to the /opt/iw/tm5/bin catalogue. Find the pushapi-util utility in the iwtm-qatools-x.x.x.xxx-release.xrpm/iwtm-qatools-x.x.x.xxx-release.x86_64.cpio/./opt/iw/tm5/bin package, where x.x.x.xxx is the build number.

    Информация
    titleNote:

    If you extract pushapi-util to a different catalogue, add the catalogue to the environment variables:

    Блок кода
    languagetext
    export PATH=$PATH:<directory>

  2. Go to the catalogue with the extracted pushapi-util utility.
  3. Make the utility file executable:

    Блок кода
    languagetext
    chmod u+x pushapi-util

Find the examples on how to call this utility in the source codes of samples or in the Примеры использования утилиты pushapi-util article.

Building PushAPI SDK samples

Find the specifics of building PushAPI SDK samples in the following articles:

Besides, SDK samples include:

  • pluging.json file – JSON scheme of mainifest.json file, which is included in the registration file for a new plugin
  • plugin.zip file – a sample of file used for registration of an external plugin

    Предупреждение
    titleWarning!

    The file contains an expired license. To use the sample file for registration of the plugin, you need to obtain a new license.