Asterisk Managment Interface (AMI), Part 1

    AMI is Asterisk's powerful and user-friendly programming interface (API) for managing the system from external programs. In addition to AMI, AGI is often used - this is an interface for launching external applications that control the Asterisk channel within a specific call. Thanks to AMI, external programs can connect to the Asterisk via the TCP protocol, initiate the execution of commands, read the result of their execution, as well as receive real-time notification of events. These mechanisms can be used, for example, in the following cases:
    • You need to know the status of the system
    • Number of active subscribers
    • Run CLI commands remotely
    • Improve CDR Storage
    • … and much more

    AMI is often used to integrate with business processes and systems, CRM software (Customer Relationship Management). It can also be used for a variety of applications, such as automatic dialers and click-to-call systems.

    Asterisk is often managed from the CLI console, but when using AMI, direct access to the server running Asterisk is not required. AMI is the simplest tool that in the hands of a developer can be a very powerful and flexible tool for integration with other software products. It enables developers to use the information generated by Asterisk in real time.

    It is also worth noting that, since version 1.6, the asterisk uses the manager version 1.1 interface. Basically, the changes affected the unification of many of the same type of commands and the standardization of responses issued by various modules. You can find out the version of the interfaces using the CoreSettings command. The version may change in the future if the AMI interface loses full compatibility with previous versions.

    How AMI Works



    A simple line-by-line protocol is used between the Asterisk server and the client program to establish communication, each message line of which consists of two lines:
    • key is a keyword describing the nature of the information contained in the current line. The keyword is not unique and can occur several times within the same premise
    • value - parameter value
    • The keyword is separated by a colon

    Next, we will use the term “package”, which will describe a series of key: value constructs separated by CRLF and completed by an additional CRLF sequence.

    The protocol of interaction between the Asterisk and the client can be described by the following characteristics:
    • Before sending commands to the Asterisk server, it is necessary to perform a client connection session with the Asterisk server;
    • Packets can be transmitted in any sequence and at any time after passing the authentication procedure;
    • The first line of the packet must contain one of the following keys: “Action” (the only option when sent by the client), and the keys “Event” and “Response” (must be sent from the Asterisk to the client);
    • The order of the lines in the package does not matter, you can use any programming language that can form packages on the client side;
    • CRLF is used to separate each line in a package and two CRLF sequences (aka \ r \ n) in order to indicate the completion of a command to the Asterisk

    AMI accepts connections established on the network port (default is TCP port 5038). The client program connects to AMI through this port and authenticates, after which the Asterisk will respond to requests and send notifications about changes in the status of the specified subsystems.
    Packet types The packet

    transmitted from the client to the Asterisk server and back is determined by the following key characteristics:
    • Action, packets sent by a client connected to AMI. After the server processes such a package, some action will be taken. There are relatively flexible restrictions on the actions performed by the client. One package - one action. The Action package should contain the name of the operation to be performed, as well as all the necessary parameters;
    • Response, defines the response sent to the Asterisk client upon the completion of the action;
    • Event, data related to the event that is generated inside the core of the Asterisk or the extension module.

    Typically, the client sends Action packets to the Asterisk (they are also called commands). The asterisk, in turn, executes the query and returns the result (often the result is the success of the action with a brief description in case of failure) received in the Response package. There is no guarantee regarding the order in which the results are received (Response packets), therefore, in the client request, the ActionID parameter is usually included in each Action packet, and the corresponding Response packet will contain the same value in the ActionID field. Thus, the client can very easily process Action and Response packets, in any desired order, without waiting for Response packets to perform the next action.

    The following CLI command (Tab completion works with autocompletion) will help to get a complete list of AMI commands available in your version of Asterisk:
    *CLI> manager show commands

    Response Packages. As written above, serve as answers to the transmitted commands. One response to the command is transmitted and can carry several values:
    • “Success” - the action is successful and all information is contained in this package
    • “Error” - an error occurred, a detailed description in the “Message” header
    • “Follows” - the result of the execution will be transmitted in subsequent Event packets

    Event packets (events) are applied in two contexts. On the one hand, they inform the client about the change in the state of the Asterisk subsystems (other changes in the channel state), and on the other hand, they transfer the data set that the Asterisk returns in response to the Action.
    • When a client sends an Action packet, the Asterisk can (in cases when it is required to return many uniform records) send a Response packet containing only the “Response: Follows” record. Next, the Asterisk sends a certain number of events containing a data set and, finally, an event that reports that all data has been sent. All Event packets generated by this contain the ActionID of the original Action packet that initiated the request. This way you can easily handle them, like Response packages. An example of an event generated by an Action is an Action Status, which triggers a Status event for each of the active channels. After all Status events are sent, the StatusComplete event is dispatched.
    • Events are created by various structural parts of the Asterisk (SIP / IAX2 / ... channels, CDR, dialplan, various parts of the core). The main task that is assigned to the events is to allow the external connected system to receive information from the Asterisk, collecting all these events, analyzing them and performing actions depending on the results obtained.

    Events are not documented in the CLI, so detailed information can be found in the documentation (file manager_1_1.txt), on voip-info.org. If you still get the impression that some event is not described, but it should be - you can find all kinds of events in the source code of the corresponding module by the function name - manager_event

    Before moving on to practical examples, it is worth noting that starting from version 1.6 Asterisk AMI has acquired version number 1.1. This is due to the reduction of the command format to a single format and a partial loss of compatibility. The article will highlight the work of version 1.6, where differences exist, explanations will be given in parentheses.
    Security

    Since the possibilities for managing the system provided through the AMI interface are almost unlimited. In addition to an unencrypted password and the ability to restrict access to AMI from various IP addresses, the Manager interface (as it is also called) has no other means of security, so it is highly recommended not to use it on public IP addresses.

    If use from the public network is necessary, then it is necessary to ensure that access is limited by using iptables or through any type of VPN tunnels. Access to the AMI interface can also be obtained through the built-in HTTP (S) server, access is configured in the http.conf file. It is worth noting that by default the AMI interface is prohibited, just like working with it through an HTTP server.

    Also in an untrusted network, if you want to provide end-user access to AMI (for example, click-2-call functionality via TAPI), we recommend using AstManProxy to handle all connections to the Manager API. About him another time.

    AMI Configuration



    In order to use the AMI interface, you need to edit the file /etc/asterisk/manager.conf, which is responsible for the configuration. The [general] section defines the general connection settings. Activates the AMI option enabled = yes. Note: For the settings to take effect, AMI must be overloaded: or Using the deny and permit options, you can specify IP addresses from which it is possible to connect to the Asterisk. You can add more users to the system (by copying the section starting with square brackets) and assign them access rights:

    [general]
    enabled=yes ; возможность работать с AMI (по-умолчанию no)
    port=5038 ; на порту TCP 5038
    bindaddr=192.168.0.1 ; принимать соединения в локальной сети (0.0.0.0 - на всех интерфейсах)
    timestampevents = yes ; Отправлять в пакетах событий временную метку
    displayconnects = yes ; Отображать факт подключения пользователя к AMI
    allowmultiplelogin = yes ; Разрешить несколько параллельных подключений с одним именем

    ; Начало секции, описывающей пользователя
    [admin] ; имя пользователя, которое определяется администратором Астериска
    secret=passwd1234 ; пароль пользователя AMI
    deny=0.0.0.0/0.0.0.0 ; запретить все ip-адреса
    permit=192.168.0.2/255.255.255.0 ; разрешить соединение только с одного ip
    read=system, call, log, verbose, command, agent, user ; список передаваемых пользователю классов событий
    write=system, call,log, verbose, command, agent, user ; список разрешенных классов команд



    *CLI>module reload manager


    *CLI>manager reload


    • read - read permissions;
    • write - write permissions.

    In the above example, the admin user was given extensive rights, up to stopping the Asterisk service (the command option is responsible for this). In subsequent versions (1.6.1 and later) it is forbidden to use commands in the AMI that can lead to an asterisk stopping.

    References





    Also popular now: