megaco

v4.9

Megaco Release Notes

This document describes the changes made to the Megaco system from version to version. The intention of this document is to list all incompatibilities as well as all enhancements and bugfixes for every release of Megaco. Each release of Megaco thus constitutes one section in this document. The title of each section is the version number of Megaco.

Megaco 4.9

Improvements and New Features

Only minor internal changes.

Own Id: OTP-19964

Megaco 4.8.2

Fixed Bugs and Malfunctions

The megaco_tcp module had debug unintentionally enabled.

Own Id: OTP-19896

Megaco 4.8.1

Fixed Bugs and Malfunctions

Documentation improvements.

Own Id: OTP-19669 Aux Id: PR-9927

Rendering of some tables in the documentation has been improved.

Own Id: OTP-19752 Aux Id: PR-10142

Megaco 4.8

Fixed Bugs and Malfunctions

Add missing spec and doc for exported functions.

Own Id: OTP-19523

Improvements and New Features

Nano seconds are now used for (example) meas result presentation.

Nanoseconds are now used, for example, in meas result presentations.

Own Id: OTP-19403

Added support for compiling Erlang/OTP for Windows on ARM64.

Own Id: OTP-19480 Aux Id: PR-8734

When compiling C/C++ code on Unix systems, the compiler hardening flags suggested by the Open Source Security Foundation are now enabled by default. To disable them, pass --disable-security-hardening-flags to configure.

Own Id: OTP-19519 Aux Id: PR-9441

Add copyright notice to files that still had none.

Own Id: OTP-19570

The license and copyright header has changed format to include an SPDX-License-Identifier. At the same time, most files have been updated to follow a uniform standard for license headers.

Own Id: OTP-19575 Aux Id: PR-9670

Tweaked some of the meas examples in order to make them benchmark compatible.

Own Id: OTP-19598

Megaco 4.7.2.1

Fixed Bugs and Malfunctions

The megaco_tcp module had debug unintentionally enabled.

Own Id: OTP-19896

Megaco 4.7.2

Fixed Bugs and Malfunctions

Corrected type spec for type mid().

Own Id: OTP-19585 Aux Id: ERIERL-1222

Megaco 4.7.1

Fixed Bugs and Malfunctions

Correct type spec for ActionReply

Own Id: OTP-19563 Aux Id: ERIERL-1216

Megaco 4.7

Improvements and New Features

Erlang/OTP type specifications has been updated to eliminate overlapping domains.

Own Id: OTP-19310 Aux Id: GH-8810, GH-8821, PR-8986

Megaco 4.6

Improvements and New Features

-callback attributes have been added to megaco_transport.

Own Id: OTP-18806 Aux Id: PR-7740

Updated types and specs for all API modules.

Own Id: OTP-18920 Aux Id: BL-322

The documentation has been migrated to use Markdown and ExDoc.

Own Id: OTP-18955 Aux Id: PR-8026

Megaco 4.5

Improvements and New Features

Make megaco transports handle gen_tcp | gen_udp with socket backend on Windows (completion).

Own Id: OTP-18599 Aux Id: OTP-18029

Megaco 4.4.4

Fixed Bugs and Malfunctions

Removed configure option --enable-sanitizers. It was untested and broken. Address sanitizer for the emulator has better support by the asan build target.

Own Id: OTP-18538 Aux Id: GH-7031, PR-7078

Megaco 4.4.3

Improvements and New Features

Replace size/1 with either tuple_size/1 or byte_size/1

The size/1 BIF is not optimized by the JIT, and its use can result in worse types for Dialyzer.

When one knows that the value being tested must be a tuple, tuple_size/1 should always be preferred.

When one knows that the value being tested must be a binary, byte_size/1 should be preferred. However, byte_size/1 also accepts a bitstring (rounding up size to a whole number of bytes), so one must make sure that the call to byte_size/ is preceded by a call to is_binary/1 to ensure that bitstrings are rejected. Note that the compiler removes redundant calls to is_binary/1, so if one is not sure whether previous code had made sure that the argument is a binary, it does not harm to add an is_binary/1 test immediately before the call to byte_size/1.

Own Id: OTP-18432 Aux Id: GH-6672,PR-6793,PR-6784,PR-6787,PR-6785,PR-6682,PR-6800,PR-6797,PR-6798,PR-6799,PR-6796,PR-6813,PR-6671,PR-6673,PR-6684,PR-6694,GH-6677,PR-6696,PR-6670,PR-6674

Megaco 4.4.2

Improvements and New Features

A very minor improvement to the measurement tool.

Own Id: OTP-18298

Megaco 4.4.1

Fixed Bugs and Malfunctions

Fixed various dialyzer related issues in the examples and the application proper.

Own Id: OTP-18179 Aux Id: ERIERL-836

Improvements and New Features

There is a new configure option, --enable-deterministic-build, which will apply the deterministic compiler option when building Erlang/OTP. The deterministic option has been improved to eliminate more sources of non-determinism in several applications.

Own Id: OTP-18165 Aux Id: PR-5965

Megaco 4.4

Improvements and New Features

Input for configure scripts adapted to autoconf 2.71.

Own Id: OTP-17414 Aux Id: PR-4967

Megaco test suite(s) use the new peer module for node starts.

Own Id: OTP-17910

Megaco 4.3

Fixed Bugs and Malfunctions

The compilation time is no longer recorded in BEAM files. There remained several undocumented functions that attempted to retrieve compilation times. Those have now been removed.

Own Id: OTP-17962

Improvements and New Features

Update the performance and debug chapters of the megaco user's guide. Also some updates to the meas tools.

Own Id: OTP-17839

Megaco 4.2

Improvements and New Features

[megaco_tcp] When connect fails, include more info in the error reason.

Own Id: OTP-17817

Megaco 4.1

Improvements and New Features

It is now possible to configure the built-in transports (megaco_tcp and megaco udp) to use the new (gen_udp- and gen_tcp-) option 'inet_backend'.

Own Id: OTP-17533

Megaco 4.0.1

Fixed Bugs and Malfunctions

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Megaco 4.0

Improvements and New Features

All the pre-v3 codec(s) (prev3a, prev3b and prev3c) was deprecated in OTP-23.0. They have now been removed.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-16560

Removed deprecated functions marked for removal.

Own Id: OTP-17049

Megaco 3.19.5.1

Fixed Bugs and Malfunctions

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Megaco 3.19.5

Fixed Bugs and Malfunctions

Fixed usage of AC_CONFIG_AUX_DIRS() macros in configure script sources.

Own Id: OTP-17093 Aux Id: ERL-1447, PR-2948

Megaco 3.19.4

Fixed Bugs and Malfunctions

Empty statistics descriptor (now) allowed in both encode and decode for version 3.

Own Id: OTP-17012 Aux Id: ERL-1405

Megaco 3.19.3

Fixed Bugs and Malfunctions

The expected number of warnings when (yecc) generating v2 and v3 (text) parser's was incorrect.

Own Id: OTP-16836

Megaco 3.19.2

Fixed Bugs and Malfunctions

The v2 and v3 parsers could not properly decode some IPv6 addresses.

Own Id: OTP-16818 Aux Id: ERIERL-526

Megaco 3.19.1

Fixed Bugs and Malfunctions

The mini parser could not properly decode some IPv6 addresses.

Own Id: OTP-16631 Aux Id: ERIERL-491

Megaco 3.19

Improvements and New Features

Refactored the internal handling of deprecated and removed functions.

Own Id: OTP-16469

The preliminary version 3 codec(s) prev3a, prev3b and prev3c has been deprecated and will be removed in OTP 24. The encoding config option 'version3' will continue to work until OTP 24.

Own Id: OTP-16531

Megaco 3.18.8.4

Fixed Bugs and Malfunctions

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Megaco 3.18.8.3

Fixed Bugs and Malfunctions

Empty statistics descriptor (now) allowed in both encode and decode for version 3.

Own Id: OTP-17012 Aux Id: ERL-1405

Megaco 3.18.8.2

Fixed Bugs and Malfunctions

The v2 and v3 parsers could not properly decode some IPv6 addresses.

Own Id: OTP-16818 Aux Id: ERIERL-526

Megaco 3.18.8.1

Fixed Bugs and Malfunctions

The mini parser could not properly decode some IPv6 addresses.

Own Id: OTP-16631 Aux Id: ERIERL-491

Megaco 3.18.8

Fixed Bugs and Malfunctions

The documented function megaco:get_sdp_record_from_PropertGroup/2 was a wrapper for megaco_sdp:get_sdp_record_from_PropertGroup/2 but did not actually exist. This has now been fixed.

Own Id: OTP-16449

Improvements and New Features

Test suite completely reworked. Add (timestamp) utility functions for debugging and testing.

Own Id: OTP-16158

Megaco 3.18.7

Fixed Bugs and Malfunctions

The meas example had not been updated for a long time, which caused it to not work. Also, it made use of deprecated functions (now()). This has now been fixed.

Own Id: OTP-16061

Megaco 3.18.6

Fixed Bugs and Malfunctions

Fix various minor issues related to Dialyzer. Mostly these are dialyzer warnings, but there was also some minor bugs detected by Dialyzer.

Own Id: OTP-15882

Megaco 3.18.5

Improvements and New Features

Minor updates to build system necessary due to move of configuration of crypto application.

Own Id: OTP-15262 Aux Id: OTP-15129

Minor adjustments made to build system for parallel configure.

Own Id: OTP-15340 Aux Id: OTP-14625

Megaco 3.18.4

Fixed Bugs and Malfunctions

Improved documentation.

Own Id: OTP-15190

Megaco 3.18.3

Fixed Bugs and Malfunctions

Removed all old unused files in the documentation.

Own Id: OTP-14475 Aux Id: ERL-409, PR-1493

Megaco 3.18.2

Improvements and New Features

Typos have been fixed.

Own Id: OTP-14387

Megaco 3.18.1

Improvements and New Features

Internal changes

Own Id: OTP-13551

Megaco 3.18

Improvements and New Features

The runtime dependencies in the application resource file have been updated.

Own Id: OTP-12762

Megaco 3.17.3

Improvements and New Features

Distribute autoconf helpers to applications at build time instead of having multiple identical copies committed in the repository.

Own Id: OTP-12348

Megaco 3.17.2

Fixed Bugs and Malfunctions

Implement --enable-sanitizers[=sanitizers]. Similar to debugging with Valgrind, it's very useful to enable -fsanitize= switches to catch bugs at runtime.

Own Id: OTP-12153

Megaco 3.17.1

Improvements and New Features

The default encoding of Erlang files has been changed from ISO-8859-1 to UTF-8.

The encoding of XML files has also been changed to UTF-8.

Own Id: OTP-10907

Megaco 3.17.0.3

Improvements and New Features

Updated doc files to utf8.

Own Id: OTP-10907

Megaco 3.17.0.2

Improvements and New Features

Introduced functionality for inspection of system and build configuration.

Own Id: OTP-11196

Megaco 3.17.0.1

Improvements and New Features

Postscript files no longer needed for the generation of PDF files have been removed.

Own Id: OTP-11016

Megaco 3.17

Version 3.17 supports code replacement in runtime from/to version 3.16.0.3 and and 3.16.0.2.

Improvements and new features

-

Fixed bugs and malfunctions

Buffer overrun error while flex scanner processing property parm groups.

This error occured only for large messages if a buffer realloc was needed while processing the property parm groups.

Own Id: OTP-10998

Aux Id: Seq 12263

Incompatibilities

-

Megaco 3.16.0.3

Version 3.16.0.2 supports code replacement in runtime from/to version 3.16.0.1, 3.16, 3.15.1.1, 3.15.1 and 3.15.

Improvements and new features

Where necessary, a comment stating encoding has been added to Erlang files. The comment is meant to be removed in Erlang/OTP R17B when UTF-8 becomes the default encoding.

Own Id: OTP-10630

Fixed bugs and malfunctions

-

Incompatibilities

A number of binary encoding alternatives has been removed. The binary encoding option driver has been removed since this (the use of the asn1 linked in driver) is now default and there is now way to not use it. See configuration of binary encoding for more info.

Megaco 3.16.0.2

Version 3.16.0.2 supports code replacement in runtime from/to version 3.16.0.1, 3.16, 3.15.1.1, 3.15.1 and 3.15.

Improvements and new features

Allow whitespaces in installation path.

It is now possible to give configure and make an installation/release path with whitespaces in it.

Own Id: OTP-10107

Fix parallel make for behaviours.

Removed use of deprecated system flag, global_haeps_size, in the measurement tool mstone1.

Fixed bugs and malfunctions

-

Incompatibilities

-

Megaco 3.16.0.1

Version 3.16.0.1 supports code replacement in runtime from/to version 3.16, 3.15.1.1, 3.15.1 and 3.15.

Improvements and new features

Fixed some faulty test cases.

Removed use of deprecated system flag, scheduler_bind_type, in the measurement tool mstone1.

Own Id: OTP-9949

Fixed bugs and malfunctions

-

Incompatibilities

-

Megaco 3.16

Version 3.16 supports code replacement in runtime from/to version 3.15.1.1, 3.15.1 and 3.15.

Improvements and new features

Minor improvements to the measurement tool mstone1.

Own Id: OTP-9604

ASN.1 no longer makes use of a driver to accelerate encode/decode, instead it uses NIFs. The encoding config option is still the same, i.e. driver.

Own Id: OTP-9672

The profiling test tool has been rewritten.

Håkan Mattsson

Own Id: OTP-9679

The flex driver has been updated to support the new driver format (changed to enable 64-bit aware drivers).

Own Id: OTP-9795

Fixed bugs and malfunctions

-

Incompatibilities

-

Megaco 3.15.1.1

Version 3.15.1.1 supports code replacement in runtime from/to version 3.15.1 and 3.15.

Improvements and new features

Correct various XML errors.

Own Id: OTP-9550

Fixed bugs and malfunctions

-

Megaco 3.15.1

Version 3.15.1 supports code replacement in runtime from/to version 3.15, 3.14.1.1, 3.14.1 and 3.14.

Improvements and new features

-

Fixed bugs and malfunctions

Fixing miscellaneous things detected by dialyzer.

Own Id: OTP-9075

Megaco 3.15

Improvements and New Features

Fixing auto-import issues.

Own Id: OTP-8842

Fixed bugs and malfunctions

-

Megaco 3.14.1.1

Version 3.14.1.1 supports code replacement in runtime from/to version 3.14.1, 3.14, 3.13, 3.12 and 3.11.3.

Improvements and new features

Updated the performance chapter.

Own Id: OTP-8696

Fixed bugs and malfunctions

-

Megaco 3.14.1

Version 3.14.1 supports code replacement in runtime from/to version 3.14, 3.13, 3.12 and 3.11.3.

Improvements and new features

A minor compiler related performance improvement.

Own Id: OTP-8561

Fixed bugs and malfunctions

A race condition when, during high load, processing both the original and a resent message and delivering this as two separate messages to the user.

Note that this solution only protects against multiple reply deliveries!

Own Id: OTP-8529

Aux Id: Seq 10915

Fix shared libraries installation.

The flex shared lib(s) were incorrectly installed as data files.

Peter Lemenkov

Own Id: OTP-8627

Eliminated a possible race condition while creating pending counters.

Own Id: OTP-8634

Aux Id: Seq 11579

Megaco 3.14

Version 3.14 supports code replacement in runtime from/to version 3.13, 3.12 and 3.11.3.

Improvements and new features

Various changes to configure and makefile(s) to facilitate cross compilation (and other build system improvements).

Own Id: OTP-8323

Added a help target in the test Makefile to explain the most useful make targets, used when testing the application using the test-server provided with megaco.

Own Id: OTP-8362

Adapted megaco_filter to the new internal format.

Own Id: OTP-8403

Fixed bugs and malfunctions

Callbacks, when the callback module is unknown (undefined), results in warning messages.

A race condition scenario. As part of a cancelation operation, replies with waiting acknowledgements is cancelled. This includes informing the user (via a call to the handle_trans_ack callback function). It is possible that at this point the connection data has been removed, which makes it impossible for megaco to perform this operation, resulting in the warning message. The solution is to also store the callback module with the other reply information, to be used when cleaning up after a cancelation.

Own Id: OTP-8328

Aux Id: Seq 11384

Megaco 3.13

Version 3.13 supports code replacement in runtime from/to version 3.12 and 3.11.3.

Improvements and new features

A minor optimization by using ets:update_element instead of ets:insert for some table updates.

Own Id: OTP-8239

The documentation is now built with open source tools (xsltproc and fop) that exists on most platforms. One visible change is that the frames are removed.

Own Id: OTP-8249

Fixed bugs and malfunctions

-

Incompatibilities

-

Introduction

Megaco/H.248 is a protocol for control of elements in a physically decomposed multimedia gateway, enabling separation of call control from media conversion. A Media Gateway Controller (MGC) controls one or more Media Gateways (MG).

This version of the stack supports version 1, 2 and 3 as defined by:

version 1 - RFC 3525 and H.248-IG (v10-v13)

version 2 - draft-ietf-megaco-h248v2-04 & H.248.1 v2 Corrigendum 1 (03/2004)

version 3 - Full version 3 as defined by ITU H.248.1 (09/2005) (including segments)

The semantics of the protocol has jointly been defined by two standardization bodies:

IETF - which calls the protocol Megaco

ITU - which calls the protocol H.248

Scope and Purpose

This manual describes the Megaco application, as a component of the Erlang/Open Telecom Platform development environment. It is assumed that the reader is familiar with the Erlang Development Environment, which is described in a separate User's Guide.

Prerequisites

The following prerequisites are required for understanding the material in the Megaco User's Guide:

the basics of the Megaco/H.248 protocol

the basics of the Abstract Syntax Notation One (ASN.1)

familiarity with the Erlang system and Erlang programming

The application requires Erlang/OTP release R10B or later.

About This Manual

In addition to this introductory chapter, the Megaco User's Guide contains the following chapters:

Chapter 2: "Architecture" describes the architecture and typical usage of the application.

Chapter 3: "Internal form and its encodings" describes the internal form of Megaco/H.248 messages and its various encodings.

Chapter 4: "Transport mechanisms" describes how different mechanisms can be used to transport the Megaco/H.248 messages.

Chapter 5: "Debugging" describes tracing and debugging.

Where to Find More Information

Refer to the following documentation for more information about Megaco/H.248 and about the Erlang/OTP development system:

version 1, RFC 3525

old version 1, RFC 3015

Version 2 Corrigendum 1

version 2, draft-ietf-megaco-h248v2-04

H.248.1 version 3

ASN.1 application User's Guide

Megaco API reference

Concurrent Programming in Erlang, 2nd Edition (1996), Prentice-Hall, ISBN 0-13-508301-X.

Architecture

Network view

Megaco is a (master/slave) protocol for control of gateway functions at the edge of the packet network. Examples of this is IP-PSTN trunking gateways and analog line gateways. The main function of Megaco is to allow gateway decomposition into a call agent (call control) part (known as Media Gateway Controller, MGC) - master, and an gateway interface part (known as Media Gateway, MG) - slave. The MG has no call control knowledge and only handle making the connections and simple configurations.

SIP and H.323 are peer-to-peer protocols for call control (valid only for some of the protocols within H.323), or more generally multi-media session protocols. They both operate at a different level (call control) from Megaco in a decomposed network, and are therefor not aware of whether or not Megaco is being used underneath.

---
title: Network architecture
---

flowchart TB
  %% Pad text (first/longest line) in node, with non-breaking spaces.
  %% This is done to force the node circle to be big enough, to fit it's text inside the circle.
  telco_network(("&nbsp;&nbsp;&nbsp;PSTN&nbsp;&nbsp;&nbsp;<br />ATM<br />etc.")) <--SS7 etc.--> signal_gw[Signaling Gateway]

  %% Alt: box with rounded left & right corners, the narrow text makes the node eliptic,
  %% slightly taller than wide
  %% telco_network(["PSTN<br />ATM<br />etc."]) <--SS7 etc.--> signal_gw[Signaling Gateway]

  signal_gw <--Sigtran--> mgc[Call Agent<br /><br /><br />Media Gateway Controller]
  telco_network <--Trunks--> trunk_gw[Trunking<br />Media Gateway]
  mgc --Megaco/H.248--> trunk_gw
  mgc --Megaco/H.248--> lines_gw[Lines<br />Media Gateway]
  lines_gw --> phone1[📞 phone 1]
  lines_gw --> phone2[📞 phone 2]
  lines_gw --> phone3[📞 ...]
  mgc --Megaco/H.248--> ip_phone_gw[IP Phone Media Gateway]

  %% Note: edges are numbered by the order they are introduced
  %% SS7
  linkStyle 0 stroke-width:5px;
  %% Sigtran
  linkStyle 1 stroke-width:3px;
  %% Trunks
  linkStyle 2 stroke-width:5px;
  %% Megaco
  linkStyle 3 stroke-width:3px;
  linkStyle 4 stroke-width:3px;
  %% phone
  linkStyle 5 stroke-width:1px;
  linkStyle 6 stroke-width:1px;
  linkStyle 7 stroke-width:1px;
  %% Megaco
  linkStyle 8 stroke-width:3px;

Megaco and peer protocols are complementary in nature and entirely compatible within the same system. At a system level, Megaco allows for

overall network cost and performance optimization

protection of investment by isolation of changes at the call control layer

freedom to geographically distribute both call function and gateway function

adaption of legacy equipment

General

This Erlang/OTP application supplies a framework for building applications that needs to utilize the Megaco/H.248 protocol.

We have introduced the term "user" as a generic term for either an MG or an MGC, since most of the functionality we support, is common for both MG's and MGC's. A (local) user may be configured in various ways and it may establish any number of connections to its counterpart, the remote user. Once a connection has been established, the connection is supervised and it may be used for the purpose of sending messages. N.B. according to the standard an MG is connected to at most one MGC, while an MGC may be connected to any number of MG's.

For the purpose of managing "virtual MG's", one Erlang node may host any number of MG's. In fact it may host a mix of MG's and MGC's. You may say that an Erlang node may host any number of "users".

The protocol engine uses callback modules to handle various things:

encoding callback modules - handles the encoding and decoding of messages. Several modules for handling different encodings are included, such as ASN.1 BER, pretty well indented text, compact text and some others. Others may be written by you.

transport callback modules - handles sending and receiving of messages. Transport modules for TCP/IP and UDP/IP are included and others may be written by you.

user callback modules - the actual implementation of an MG or MGC. Most of the functions are intended for handling of a decoded transaction (request, reply, acknowledgement), but there are others that handles connect, disconnect and errors cases.

Each connection may have its own configuration of callback modules, re-send timers, transaction id ranges etc. and they may be re-configured on-the-fly.

In the API of Megaco, a user may explicitly send action requests, but generation of transaction identifiers, the encoding and actual transport of the message to the remote user is handled automatically by the protocol engine according to the actual connection configuration. Megaco messages are not exposed in the API.

On the receiving side the transport module receives the message and forwards it to the protocol engine, which decodes it and invokes user callback functions for each transaction. When a user has handled its action requests, it simply returns a list of action replies (or a message error) and the protocol engine uses the encoding module and transport module to compose and forward the message to the originating user.

The protocol stack does also handle things like automatic sending of acknowledgements, pending transactions, re-send of messages, supervision of connections etc.

In order to provide a solution for scalable implementations of MG's and MGC's, a user may be distributed over several Erlang nodes. One of the Erlang nodes is connected to the physical network interface, but messages may be sent from other nodes and the replies are automatically forwarded back to the originating node.

Single node config

Here a system configuration with an MG and MGC residing in one Erlang node each is outlined:

---
title: Single node config
---

flowchart LR
  subgraph MG
    mg_user[MG User]
    enc_dec1[enc/dec] <--> proto_engine1[Protocol Engine]
    transport1[Transport Layer]
  end
  subgraph MGC
    mgc_user[MGC User]
    proto_engine2[Protocol Engine]
    enc_dec2[enc/dec] <--> proto_engine2
    transport2[Transport Layer]
  end
  mg_user <-.-> mgc_user
  transport1 <--> transport2
  transport1 <-.-> transport2

Distributed config

In a larger system with a user (in this case an MGC) distributed over several Erlang nodes, it looks a little bit different. Here the encoding is performed on the originating Erlang node (1) and the binary is forwarded to the node (2) with the physical network interface. When the potential message reply is received on the interface on node (2), it is decoded there and then different actions will be taken for each transaction in the message. The transaction reply will be forwarded in its decoded form to the originating node (1) while the other types of transactions will be handled locally on node (2).

Timers and re-send of messages will be handled on locally on one node, that is node(1), in order to avoid unnecessary transfer of data between the Erlang nodes.

---
title: Distributed config
---

flowchart
  subgraph MG
    mg_user[MG User]
    enc_dec[enc/dec] <--> proto_engine3[Protocol Engine]
    transport3[Transport Layer]
  end
  subgraph Conceptual MGC
    subgraph node 1
      mgc_user[MGC User]
      proto_engine1[Protocol Engine]
      enc <--> proto_engine1
    end
    subgraph node 2
      proto_engine2[Protocol Engine]
      dec <--> proto_engine2
      transport2[Transport Layer]
    end
    proto_engine1 <--> proto_engine2
  end
  mg_user <-.-> mgc_user
  transport3 <--> transport2
  transport3 <-.-> transport2

Message round-trip call flow

The typical round-trip of a message can be viewed as follows. Firstly we view the call flow on the originating side:

---
title: Message Call Flow (originating side)
---

sequenceDiagram
    participant user
    participant main
    participant encoder
    participant transport
    participant network as transport layer

    user ->> main: megaco:cast/3
    main ->> encoder: EncMod:encode_message/2
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send bytes(1)
    network ->> transport: receive bytes(2)
    transport ->> main: megaco:receive_message/4
    main ->> encoder: EncMod:decode_message/4
    encoder ->> main:
    note over main, encoder: (ack requested)
    main ->> encoder: EncMod:encode_message
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send bytes(3)
    encoder ->> user: UserMod:handle_trans_reply/4

Then we continue with the call flow on the destination side:

---
title: Message Call Flow (destination side)
---

sequenceDiagram
    participant network as transport layer
    participant transport
    participant main
    participant encoder
    participant user

    network ->> transport: receive bytes(1)
    transport ->> main: megaco:receive_message/2
    main ->> encoder: EncMod:decode_message/2
    encoder ->> main:
    main ->> user: UserMod:handle_trans_request/3
    user ->> main:
    main ->> encoder: EncMod:encode_message/2
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send bytes(2)
    network ->> transport: receive bytes(3)
    transport ->> main: megaco:receive_message/4
    main ->> encoder: EncMod:decode_message/2
    encoder ->> main:
    main ->> user: UserMod:handle_trans_ack/4
    user ->> main:

Running the stack

Starting

A user may have a number of "virtual" connections to other users. An MG is connected to at most one MGC, while an MGC may be connected to any number of MG's. For each connection the user selects a transport service, an encoding scheme and a user callback module.

An MGC must initiate its transport service in order to listen to MG's trying to connect. How the actual transport is initiated is outside the scope of this application. However a send handle (typically a socket id or host and port) must be provided from the transport service in order to enable us to send the message to the correct destination. We do however not assume anything about this, from our point of view, opaque handle. Hopefully it is rather small since it will passed around the system between processes rather frequently.

A user may either be statically configured in a .config file according to the application concept of Erlang/OTP or dynamically started with the configuration settings as arguments to megaco:start_user/2. These configuration settings may be updated later on with megaco:update_conn_info/2.

The function megaco:connect/4 is used to tell the Megaco application about which control process it should supervise, which MID the remote user has, which callback module it should use to send messages etc. When this "virtual" connection is established the user may use megaco:call/3 and megaco:cast/3 in order to send messages to the other side. Then it is up to the MG to send its first Service Change Request message after applying some clever algorithm in order to fight the problem with startup avalanche (as discussed in the RFC).

The originating user will wait for a reply or a timeout (defined by the request_timer). When it receives the reply this will optionally be acknowledged (regulated by auto_ack), and forwarded to the user. If an interim pending reply is received, the long_request_timer will be used instead of the usual request_timer, in order to enable avoidance of spurious re-sends of the request.

On the destination side the transport service waits for messages. Each message is forwarded to the Megaco application via the megaco:receive_message/4 callback function. The transport service may or may not provide means for blocking and unblocking the reception of the incoming messages.

If a message is received before the "virtual" connection has been established, the connection will be setup automatically. An MGC may be real open minded and dynamically decide which encoding and transport service to use depending on how the transport layer contact is performed. For IP transports two ports are standardized, one for textual encoding and one for binary encoding. If for example an UDP packet was received on the text port it would be possible to decide encoding and transport on the fly.

After decoding a message various user callback functions are invoked in order to allow the user to act properly. See the megaco_user module for more info about the callback arguments.

When the user has processed a transaction request in its callback function, the Megaco application assembles a transaction reply, encodes it using the selected encoding module and sends the message back by invoking the callback function:

SendMod:send_message(SendHandle, ErlangBinary)

Re-send of messages, handling pending transactions, acknowledgements etc. is handled automatically by the Megaco application but the user is free to override the default behaviour by the various configuration possibilities. See megaco:update_user_info/2 and megaco:update_conn_info/2 about the possibilities.

When connection gets broken (that is explicitly by megaco:disconnect/2 or when its controlling process dies) a user callback function is invoked in order to allow the user to re-establish the connection. The internal state of kept messages, re-send timers etc. is not affected by this. A few re-sends will of course fail while the connection is down, but the automatic re-send algorithm does not bother about this and eventually when the connection is up and running the messages will be delivered if the timeouts are set to be long enough. The user has the option of explicitly invoking megaco:cancel/2 to cancel all messages for a connection.

MGC startup call flow

In order to prepare the MGC for the reception of the initial message, hopefully a Service Change Request, the following needs to be done:

Start the Megaco application.

Start the MGC user. This may either be done explicitly with megaco:start_user/2 or implicitly by providing the -megaco users configuration parameter.

Initiate the transport service and provide it with a receive handle obtained from megaco:user_info/2.

When the initial message arrives the transport service forwards it to the protocol engine which automatically sets up the connection and invokes UserMod:handle_connect/2 before it invokes UserMod:handle_trans_request/3 with the Service Change Request like this:

---
title: MGC Startup Call Flow
---

sequenceDiagram
    participant network as network layer
    participant transport
    participant main
    participant encoder
    participant user

    network ->> transport: receive bytes(1)
    transport ->> main: megaco:receive_message/4
    main ->> encoder: EncMod:decode_message/2
    encoder ->> main:
    main ->> user: UserMod:handle_connect/3
    user ->> main:
    main ->> encoder: EncMod:encode_message/2
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send bytes(2)

MG startup call flow

In order to prepare the MG for the sending of the initial message, hopefully a Service Change Request, the following needs to be done:

Start the Megaco application.

Start the MG user. This may either be done explicitly with megaco:start_user/2 or implicitly by providing the -megaco users configuration parameter.

Initiate the transport service and provide it with a receive handle obtained from megaco:user_info/2.

Setup a connection to the MGC with megaco:connect/4 and provide it with a receive handle obtained from megaco:user_info/2.

If the MG has been provisioned with the MID of the MGC it can be given as the RemoteMid parameter to megaco:connect/4 and the call flow will look like this:

---
title: MG Startup Call Flow
---

sequenceDiagram
    participant user
    participant main
    participant encoder
    participant transport
    participant network as network layer

    user ->> main: megaco:connect/4
    main ->> user: UserMod:handle_connect/2
    user ->> main:
    main ->> user: (return of megaco:connect/4)
    user ->> main: megaco:call/3
    main ->> encoder: EncMod:encode_message/2
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send_bytes(1)
    network ->> transport: receive bytes(2)
    transport ->> main: megaco:receive_message/4
    main ->> encoder: EncMode:decode_message/2
    encoder ->> main:
    main ->> user: (return of megaco:call/3)

If the MG cannot be provisioned with the MID of the MGC, the MG can use the atom 'preliminary_mid' as the RemoteMid parameter to megaco:connect/4 and the call flow will look like this:

---
title: MG Startup Call Flow (preliminary_mid)
---

sequenceDiagram
    participant user
    participant main
    participant encoder
    participant transport
    participant network as network layer

    user ->> main: megaco:connect/4 (RemoteMid = preliminary_mid)
    main ->> user: UserMod:handle_connect/2 (RemoteMid = preliminary_mid)
    user ->> main:
    main ->> user: (return of megaco:connect/4)
    user ->> main: megaco:call/3
    main ->> encoder: EncMod:encode_message/2
    encoder ->> main:
    main ->> transport: SendMod:send_message/2
    transport ->> network: send_bytes(1)
    network ->> transport: receive bytes(2)
    transport ->> main: megaco:receive_message/4
    main ->> encoder: EncMode:decode_message/2
    encoder ->> main:
    main ->> user: (UserMod:handle_connect/2 (RemoteMid = actual_mid of MGC))
    user ->> main:
    main ->> user: (return of megaco:call/3)

Configuring the Megaco stack

There are three kinds of configuration:

User info - Information related to megaco users. Read/Write.

A User is an entity identified by a MID, e.g. a MGC or a MG.

This information can be retrieved using megaco:user_info.

Connection info - Information regarding connections. Read/Write.

This information can be retrieved using megaco:conn_info.

System info - System wide information. Read only.

This information can be retrieved using megaco:system_info.

Initial configuration

The initial configuration of the Megaco should be defined in the Erlang system configuration file. The following configured parameters are defined for the Megaco application:

users = [{Mid, [user_config()]}].

Each user is represented by a tuple with the Mid of the user and a list of config parameters (each parameter is in turn a tuple: {Item, Value}).

scanner = flex | {Module, Function, Arguments, Modules}

flex will result in the start of the flex scanner with default options.

The MFA alternative makes it possible for Megaco to start and supervise a scanner written by the user (see supervisor:start_child for an explanation of the parameters).

See also Configuration of text encoding module(s) for more info.

Changing the configuration

The configuration can be changed during runtime. This is done with the functions megaco:update_user_info and megaco:update_conn_info

The transaction sender

The transaction sender is a process (one per connection), which handle all transaction sending, if so configured (see megaco:user_info and megaco:conn_info).

The purpose of the transaction sender is to accumulate transactions for a more efficient message sending. The transactions that are accumulated are transaction request and transaction ack. For transaction ack's the benefit is quite large, since the transactions are small and it is possible to have ranges (which means that transaction acks for transactions 1, 2, 3 and 4 can be sent as a range 1-4 in one transaction ack, instead of four separate transactions).

There are a number of configuration parameter's that control the operation of the transaction sender. In principle, a message with everything stored (ack's and request's) is sent from the process when:

When trans_timer expires.

When trans_ack_maxcount number of ack's has been received.

When trans_req_maxcount number of requests's has been received.

When the size of all received requests exceeds trans_req_maxsize.

When a reply transaction is sent.

When a pending transaction is sent.

When something is to be sent, everything is packed into one message, unless the trigger was a reply transaction and the added size of the reply and all the requests is greater then trans_req_maxsize, in which case the stored transactions are sent first in a separate message and the reply in another message.

When the transaction sender receives a request which is already "in storage" (indicated by the transaction id) it is assumed to be a resend and everything stored is sent. This could happen if the values of the trans_timer and the request_timer is not properly chosen.

Segmentation of transaction replies

In version 3 of the megaco standard, the concept of segmentation package was introduced. Simply, this package defines a procedure to segment megaco messages (transaction replies) when using a transport that does not automatically do this (e.g. UDP).

Although it would be both pointless and counterproductive to use segmentation on a transport that already does this (e.g. TCP), the megaco application does not check this. Instead, it is up to the user to configure this properly.

Receiving segmented messages:

This is handled automatically by the megaco application. There is however one thing that need to be configured by the user, the segment_recv_timer option.

Note that the segments are delivered to the user differently depending on which function is used to issue the original request. When issuing the request using the megaco:cast function, the segments are delivered to the user via the handle_trans_reply callback function one at a time, as they arrive. But this obviously does not work for the megaco:call function. In this case, the segments are accumulated and then delivered all at once as the function returns.

Sending segmented messages:

This is also handled automatically by the megaco application. First of all, segmentation is only attempted if so configured, see the segment_send option. Secondly, megaco relies on the ability of the used codec to encode action replies, which is the smallest component the megaco application handles when segmenting. Thirdly, the reply will be segmented only if the sum of the size of the action replies (plus an arbitrary message header size) are greater then the specified max message size (see the max_pdu_size option). Finally, if segmentation is decided, then each action reply will make up its own (segment) message.

Internal form and its encodings

This version of the stack is compliant with:

Megaco/H.248 version 1 (RFC3525) updated according to Implementors Guide version 10-13.

Megaco/H.248 version 2 as defined by draft-ietf-megaco-h248v2-04 updated according to Implementors Guide version 10-13.

Megaco/H.248 version 3 as defined by ITU H.248.1 (09/2005).

Internal form of messages

We use the same internal form for both the binary and text encoding. Our internal form of Megaco/H.248 messages is heavily influenced by the internal format used by ASN.1 encoders/decoders:

"SEQUENCE OF" is represented as a list.

"CHOICE" is represented as a tagged tuple with size 2.

"SEQUENCE" is represented as a record, defined in "megaco/include/megaco_message_v1.hrl".

"OPTIONAL" is represented as an ordinary field in a record which defaults to 'asn1_NOVALUE', meaning that the field has no value.

"OCTET STRING" is represented as a list of unsigned integers.

"ENUMERATED" is represented as a single atom.

"BIT STRING" is represented as a list of atoms.

"BOOLEAN" is represented as the atom 'true' or 'false'.

"INTEGER" is represented as an integer.

"IA5String" is represented as a list of integers, where each integer is the ASCII value of the corresponding character.

"NULL" is represented as the atom 'NULL'.

In order to fully understand the internal form you must get hold on a ASN.1 specification for the Megaco/H.248 protocol, and apply the rules above. Please, see the documentation of the ASN.1 compiler in Erlang/OTP for more details of the semantics in mapping between ASN.1 and the corresponding internal form.

Observe that the 'TerminationId' record is not used in the internal form. It has been replaced with a megaco_term_id record (defined in "megaco/include/megaco.hrl").

The different encodings

The Megaco/H.248 standard defines both a plain text encoding and a binary encoding (ASN.1 BER) and we have implemented encoders and decoders for both. We do in fact supply five different encoding/decoding modules.

In the text encoding, implementors have the choice of using a mix of short and long keywords. It is also possible to add white spaces to improve readability. We use the term compact for text messages with the shortest possible keywords and no optional white spaces, and the term pretty for a well indented text format using long keywords and an indentation style like the text examples in the Megaco/H.248 specification).

Here follows an example of a text message to give a feeling of the difference between the pretty and compact versions of text messages. First the pretty, well indented version with long keywords:

   MEGACO/1 [124.124.124.222]
   Transaction = 9998 {
           Context = - {
                   ServiceChange = ROOT {
                           Services {
                                   Method = Restart,
                                   ServiceChangeAddress = 55555,
                                   Profile = ResGW/1,
                                   Reason = "901 Cold Boot"
                           }
                   }
           }
   }

Then the compact version without indentation and with short keywords:

   !/1 [124.124.124.222]
   T=9998{C=-{SC=ROOT{SV{MT=RS,AD=55555,PF=ResGW/1,RE="901 Cold Boot"}}}}

And the programmers view of the same message. First a list of ActionRequest records are constructed and then it is sent with one of the send functions in the API:

  Prof = #'ServiceChangeProfile'{profileName = "resgw", version = 1},
  Parm = #'ServiceChangeParm'{serviceChangeMethod  = restart,
                              serviceChangeAddress = {portNumber, 55555},
                              serviceChangeReason  = "901 Cold Boot",
                              serviceChangeProfile = Prof},
  Req = #'ServiceChangeRequest'{terminationID = [?megaco_root_termination_id],
                                serviceChangeParms = Parm},
  Actions = [#'ActionRequest'{contextId = ?megaco_null_context_id,
                              commandRequests = {serviceChangeReq, Req}}],
  megaco:call(ConnHandle, Actions, Config).

And finally a print-out of the entire internal form:

  {'MegacoMessage',
   asn1_NOVALUE,
   {'Message',
    1,
    {ip4Address,{'IP4Address', [124,124,124,222], asn1_NOVALUE}},
    {transactions,
     [
      {transactionRequest,
       {'TransactionRequest',
         9998,
         [{'ActionRequest',
           0,
           asn1_NOVALUE,
           asn1_NOVALUE,
           [
            {'CommandRequest',
             {serviceChangeReq,
              {'ServiceChangeRequest',
               [
                {megaco_term_id, false, ["root"]}],
                {'ServiceChangeParm',
                 restart,
                 {portNumber, 55555},
                 asn1_NOVALUE,
                 {'ServiceChangeProfile', "resgw", version = 1},
                 "901 MG Cold Boot",
                 asn1_NOVALUE,
                 asn1_NOVALUE,
                 asn1_NOVALUE
                }
              }
             },
             asn1_NOVALUE,
             asn1_NOVALUE
            }
           ]
          }
         ]
       }
      }
     ]
    }
   }
  }

The following encoding modules are provided:

megaco_pretty_text_encoder - encodes messages into pretty text format, decodes both pretty as well as compact text.

megaco_compact_text_encoder - encodes messages into compact text format, decodes both pretty as well as compact text.

megaco_binary_encoder - encode/decode ASN.1 BER messages. This encoder implements the fastest of the BER encoders/decoders. Recommended binary codec.

megaco_ber_encoder - encode/decode ASN.1 BER messages.

megaco_per_encoder - encode/decode ASN.1 PER messages. N.B. that this format is not included in the Megaco standard.

megaco_erl_dist_encoder - encodes messages into Erlangs distribution format. It is rather verbose but encoding and decoding is blinding fast. N.B. that this format is not included in the Megaco standard.

Configuration of Erlang distribution encoding module

The encoding_config of the megaco_erl_dist_encoder module may be one of these:

[] - Encodes the messages to the standard distribution format. It is rather verbose but encoding and decoding is blinding fast.

[megaco_compressed] - Encodes the messages to the standard distribution format after an internal transformation. It is less verbose, but the total time of the encoding and decoding will on the other hand be somewhat slower (see the performance chapter for more info).

[{megaco_compressed, Module}] - Works in the same way as the megaco_compressed config parameter, only here the user provide their own compress module. This module must implement the megaco_edist_compress behaviour.

[compressed] - Encodes the messages to a compressed form of the standard distribution format. It is less verbose, but the encoding and decoding will on the other hand be slower.

Configuration of text encoding module(s)

When using text encoding(s), there is actually two different configs controlling what software to use:

[] - An empty list indicates that the erlang scanner should be used.

[{flex, port()}] - Use the flex scanner when decoding (not optimized for SMP). See initial configuration for more info.

[{flex, ports()}] - Use the flex scanner when decoding (optimized for SMP). See initial configuration for more info.

The Flex scanner is a Megaco scanner written as a linked in driver (in C). There are two ways to get this working:

Let the Megaco stack start the flex scanner (load the driver).

To make this happen the megaco stack has to be configured:

Add the {scanner, flex} (or similar) directive to an Erlang system config file for the megaco app (see initial configuration chapter for details).

Retrieve the encoding-config using the system_info function (with Item = text_config).

Update the receive handle with the encoding-config (the encoding_config field).

The benefit of this is that Megaco handles the starting, holding and the supervision of the driver and port.

The Megaco client (user) starts the flex scanner (load the driver).

When starting the flex scanner a port to the linked in driver is created. This port has to be owned by a process. This process must not die. If it does the port will also terminate. Therefor:

Create a permanent process. Make sure this process is supervised (so that if it does die, this will be noticed).

Let this process start the flex scanner by calling the megaco_flex_scanner:start/0,1 function.

Retrieve the encoding-config and when initiating the megaco_receive_handle, set the field encoding_config accordingly.

Pass the megaco_receive_handle to the transport module.

Configuration of binary encoding module(s)

When using binary encoding, the structure of the termination id's needs to be specified.

[native] - skips the transformation phase, i.e. the decoded message(s) will not be transformed into our internal form.

[integer()] - A list containing the size (the number of bits) of each level. Example: [3,8,5,8].

integer/0 - Number of one byte (8 bits) levels. N.B. This is currently converted into the previous config. Example: 3 ([8,8,8]).

Handling megaco versions

There are two ways to handle the different megaco encoding versions. Either using dynamic version detection (only valid for for incoming messages) or by explicit version setting in the connection info.

For incoming messages:

Dynamic version detection

Set the protocol version in the megaco_receive_handle to dynamic (this is the default).
This works for those codecs that support partial decode of the version, currently text, and ber_bin (megaco_binary_encoder and megaco_ber_bin_encoder).
This way the decoder will detect which version is used and then use the proper decoder.

Explicit version

Explicitly set the actual protocol version in the megaco_receive_handle. Start with version 1. When the initial service change has been performed and version 2 has been negotiated, upgrade the megaco_receive_handle of the transport process (control_pid) to version 2. See megaco_tcp and megaco_udp.
Note that if udp is used, the same transport process could be used for several connections. This could make upgrading impossible.
For codecs that does not support partial decode of the version, currently megaco_ber_encoder and megaco_per_encoder, dynamic will revert to version 1.

For outgoing messages:

Update the connection info protocol_version.

Override protocol version when sending a message by adding the item {protocol_version, integer()} to the Options. See call or cast.
Note that this does not effect the messages that are sent autonomously by the stack. They use the protocol_version of the connection info.

Encoder callback functions

The encoder callback interface is defined by the megaco_encoder behaviour, see megaco_encoder.

Transport mechanisms

Callback interface

The callback interface of the transport module contains several functions. Some of which are mandatory while others are only optional:

send_message - Send a message. Mandatory

block - Block the transport. Optional

This function is useful for flow control.

unblock - Unblock the transport. Optional

For more detail, see the megaco_transport behaviour definition.

Examples

The Megaco/H.248 application contains implementations for the two protocols specified by the Megaco/H.248 standard; UDP, see megaco_udp, and TCP/TPKT, see megaco_tcp.

Implementation examples

A simple Media Gateway Controller

In megaco/examples/simple/megaco_simple_mgc.erl there is an example of a simple MGC that listens on both text and binary standard ports and is prepared to handle a Service Change Request message to arrive either via TCP/IP or UDP/IP. Messages received on the text port are decoded using a text decoder and messages received on the binary port are decoded using a binary decoder.

The Service Change Reply is encoded in the same way as the request and sent back to the MG with the same transport mechanism UDP/IP or TCP/IP.

After this initial service change message the connection between the MG and MGC is fully established and supervised.

The MGC, with its four listeners, may be started with:

      cd megaco/examples/simple
      erl -pa ../../../megaco/ebin -s megaco_filter -s megaco
      megaco_simple_mgc:start().

or simply 'make mgc'.

The -s megaco_filter option to erl implies, the event tracing mechanism to be enabled and an interactive sequence chart tool to be started. This may be quite useful in order to visualize how your MGC interacts with the Megaco/H.248 protocol stack.

The event traces may alternatively be directed to a file for later analyze. By default the event tracing is disabled, but it may dynamically be enabled without any need for re-compilation of the code.

A simple Media Gateway

In megaco/examples/simple/megaco_simple_mg.erl there is an example of a simple MG that connects to an MGC, sends a Service Change Request and waits synchronously for a reply.

After this initial service change message the connection between the MG and MGC is fully established and supervised.

Assuming that the MGC is started on the local host, four different MG's, using text over TCP/IP, binary over TCP/IP, text over UDP/IP and binary over UDP/IP may be started on the same Erlang node with:

      cd megaco/examples/simple
      erl -pa ../../../megaco/ebin -s megaco_filter -s megaco
      megaco_simple_mg:start().

or simply 'gmake mg'.

If you "only" want to start a single MG which tries to connect an MG on a host named "baidarka", you may use one of these functions (instead of the megaco_simple_mg:start/0 above):

      megaco_simple_mg:start_tcp_text("baidarka", []).
      megaco_simple_mg:start_tcp_binary("baidarka", []).
      megaco_simple_mg:start_udp_text("baidarka", []).
      megaco_simple_mg:start_udp_binary("baidarka", []).

The -s megaco_filter option to erl implies, the event tracing mechanism to be enabled and an interactive sequence chart tool to be started. This may be quite useful in order to visualize how your MG interacts with the Megaco/H.248 protocol stack.

The event traces may alternatively be directed to a file for later analyze. By default the event tracing is disabled, but it may dynamically be enabled without any need for re-compilation of the code.

Megaco mib

Intro

The Megaco mib is as of yet not standardized and our implementation is based on draft-ietf-megaco-mib-04.txt. Almost all of the mib cannot easily be implemented by the megaco application. Instead these things should be implemented by a user (of the megaco application).

So what part of the mib is implemented? Basically the relevant statistic counters of the MedGwyGatewayStatsEntry.

Statistics counters

The implementation of the statistic counters is lightweight. I.e. the statistic counters are handled separately by different entities of the application. For instance our two transport module(s) (see megaco_tcp and megaco_udp) maintain their own counters and the application engine (see megaco) maintain its own counters.

This also means that if a user implement their own transport service then it has to maintain its own statistics.

Distribution

Each megaco application maintains its own set of counters. So in a large (distributed) MG/MGC it could be necessary to collect the statistics from several nodes (each) running the megaco application (only one of them with the transport).

Performance comparison

Comparison of encoder/decoders

The Megaco/H.248 standard defines both a plain text encoding and a binary encoding (ASN.1 BER) and we have implemented encoders and decoders for both. We do supply a bunch of different encoding/decoding modules and the user may in fact implement their own (like our erl_dist module). Using a non-standard encoding format has its obvious drawbacks, but may be useful in some configurations.

We have made four different measurements of our Erlang/OTP implementation of the Megaco/H.248 protocol stack, in order to compare our different encoders/decoders. The result of each one is summarized in the table below.

Codec and config | Size | Encode | Decode | Total
pretty | 336 | 5 | 12 | 17
pretty [flex] | 336 | 5 | 11 | 16
compact | 181 | 4 | 10 | 14
compact [flex] | 181 | 4 | 9 | 13
per bin | 91 | 6 | 6 | 12
per bin [native] | 91 | 4 | 3 | 7
ber bin | 165 | 6 | 6 | 12
ber bin [native] | 165 | 4 | 3 | 7
erl_dist | 875 | 2 | 5 | 7
erl_dist [megaco_compressed] | 405 | 1 | 2 | 3
erl_dist [compressed] | 345 | 15 | 9 | 24
erl_dist [megaco_compressed,compressed] | 200 | 11 | 4 | 15

Table: Codec performance

Description of encoders/decoders

In Appendix A of the Megaco/H.248 specification (RFC 3525), there are about 30 messages that shows a representative call flow. We have also added a few extra version 1, version 2 and version 3 messages. We have used these messages as basis for our measurements. Our figures have not been weighted in regard to how frequent the different kinds of messages that are sent between the media gateway and its controller.

The test compares the following encoder/decoders:

pretty - pretty printed text. In the text encoding, the protocol stack implementors have the choice of using a mix of short and long keywords. It is also possible to add white spaces to improve readability. The pretty text encoding utilizes long keywords and an indentation style like the text examples in the Megaco/H.248 specification.

compact - the compact text encoding uses the shortest possible keywords and no optional white spaces.

ber - ASN.1 BER.

per - ASN.1 PER. Not standardized as a valid Megaco/H.248 encoding, but included for the matter of completeness as its encoding is extremely compact.

erl_dist - Erlang's native distribution format. Not standardized as a valid Megaco/H.248 encoding, but included as a reference due to its well known performance characteristics. Erlang is a dynamically typed language and any Erlang data structure may be serialized to the erl_dist format by using built-in functions.

The actual encoded messages have been collected in one directory per encoding type, containing one file per encoded message.

Here follows an example of a text message to give a feeling of the difference between the pretty and compact versions of text messages. First the pretty printed, well indented version with long keywords:

MEGACO/1 [124.124.124.222]
  Transaction = 9998 {
    Context = - {
      ServiceChange = ROOT {
        Services {
          Method = Restart,
          ServiceChangeAddress = 55555,
          Profile = ResGW/1,
          Reason = "901 MG Cold Boot"
        }
      }
    }
  }

Then the compact text version without indentation and with short keywords:

!/1 [124.124.124.222] T=9998{
  C=-{SC=ROOT{SV{MT=RS,AD=55555,PF=ResGW/1,RE="901 MG Cold Boot"}}}}

Setup

The measurements has been performed on a Dell Precision 5550 Laptop with a Intel(R) Core(TM) i7-10875H CPU @ 2.30GHz, with 40 GB memory and running Ubuntu 20.04 x86_64, kernel 5.4.0-91-generic. Software versions was open source OTP 24.2 (megaco-4.2).

Summary

In our measurements we have seen that there are no significant differences in message sizes between ASN.1 BER and the compact text format. Some care should be taken when using the pretty text style (which is used in all the examples included in the protocol specification and preferred during debugging sessions) since the messages can then be quite large. If the message size really is a serious issue, our per encoder should be used, as the ASN.1 PER format is much more compact than all the other alternatives. Its major drawback is that it is has not been approved as a valid Megaco/H.248 message encoding.

When it comes to pure encode/decode performance, it turns out that:

our fastest binary encoder (ber) is about equal to our fastest text encoder (compact).

our fastest binary decoder (ber) is about 66% faster than our fastest text decoder (compact).

If the pure encode/decode performance really is a serious issue, our erl_dist encoder could be used, as the encoding/decoding of the erlang distribution format is much faster than all the other alternatives. Its major drawback is that it is has not been approved as a valid Megaco/H.248 message encoding.

There is no performance advantage of building (and using) a non-reentrant flex scanner over a reentrant flex scanner (if flex supports building such a scanner).

Note

Please, observe that these performance figures are related to our implementation in Erlang/OTP. Measurements of other implementations using other tools and techniques may of course result in other figures.

Testing and tools

Tracing

We have instrumented our code in order to enable tracing. Running the application with tracing deactivated, causes a negligible performance overhead (an external call to a function which returns an atom). Activation of tracing does not require any recompilation of the code, since we rely on Erlang/OTP's built in support for dynamic trace activation. In our case tracing of calls to a given external function.

Event traces can be viewed in a generic message sequence chart tool, et, or as standard output (events are written to stdio).

See enable_trace, disable_trace and set_trace for more info.

Measurement and transformation

We have included some simple tool(s) for codec measurement (meas), performance tests (mstone1 and mstone2) and message transformation.

The tool(s) are located in the example/meas directory.

Requirement

Erlang/OTP, version 24.2 or later.

Version 4.2 or later of this application.

Version 5.0.17 or later of the asn1 application.

The flex libraries. Without it, the flex powered codecs cannot be used.

Meas results

The results from the measurement run (meas) is four excel-compatible textfiles:

decode_time.xls -> Decoding result

encode_time.xls -> Encoding result

total_time.xls -> Total (Decoding+encoding) result

message_size.xls -> Message size

Instruction

The tool contain four things:

The transformation module

The measurement (meas) module(s)

The mstone (mstone1 and mstone2) module(s)

The basic message file

Message Transformation

The messages used by the different tools are contained in single message package file (see below for more info). The messages in this file is encoded with just one codec. During measurement initiation, the messages are read and then transformed to all codec formats used in the measurement.

The message transformation is done by the transformation module. It is used to transform a set of messages encoded with one codec into the other base codec's.

Measurement(s)

There are two different measurement tools:

meas:

Used to perform codec measurements. That is, to see what kind of performance can be expected by the different codecs provided by the megaco application.

The measurement is done by iterating over the decode/encode function for approx 2 seconds per message and counting the number of decodes/encodes.

Is best run by modifying the meas.sh.skel skeleton script provided by the tool.

To run it manually do the following:

        % erl -pa <path-megaco-ebin-dir> -pa <path-to-meas-module-dir>
        Erlang (BEAM) emulator version 5.6 [source]

        Eshell V12.2  (abort with ^G)
        1> megaco_codec_meas:start().
        ...
        2> halt().

or to make it even easier, assuming a measure shall be done on all the codecs (as above):

        % erl -noshell -pa <path-megaco-ebin-dir> \\
              -pa <path-to-meas-module-dir> \\
              -s megaco_codec_meas -s init stop

When run as above (this will take some time), the measurement process is done as follows:

For each codec:
    For each message:
        Read the message from the file
            Detect message version
            Measure decode
                Measure encode
          Write results, encode, decode and total, to file

mstone1 and mstone2:

These are two different SMP performance monitoring tool(s).

mstone1 creates a process for each codec config supported by the megaco application and let them run for a specific time (all at the same time), encoding and decoding megaco messages. The number of messages processed in total is the mstone1(1) value.

There are different ways to run the mstone1 tool, e.g. with or without the use of drivers, with only flex-empowered configs.

Is best run by modifying the mstone1.sh.skel skeleton script provided by the tool.

The mstone2 is similar to the mstone1 tool, but in this case, each created process makes only one run through the messages and then exits. A soon as a process exits, a new process (with the same config and messages) is created to takes its place. The number of messages processed in total is the mstone2(1) value.

Both these tools use the message package (time_test.msgs) provided with the tool(s), although it can run on any message package as long as it has the same structure.

Message package file

This is simply an erlang compatible text-file with the following structure: {codec_name(), messages_list()}.

codec_name() = pretty | compact | ber | per | erlang      (how the messages are encoded)
messages_list() = [{message_name(), message()}]
message_name() = atom()
message() = binary()

The codec name is the name of the codec with which all messages in the message_list() has been encoded.

This file can be exported to a file structure by calling the export_messages function. This can be usefull if a measurement shall be done with an external tool. Exporting the messages creates a directory tree with the following structure:

<message package>/pretty/<message-files>
                  compact/
                  per/
                  ber/<message-files>
                  erlang/

The file includes both version 1, 2 and version 3 messages.

Notes

Binary codecs

There are two basic ways to use the binary encodings: With package related name and termination id transformation (the 'native' encoding config) or without. This transformation converts package related names and termination id's to a more convenient internal form (equivalent with the decoded text message).

The transformation is done _after_ the actual decode has been done.

Therefor in the tests, binary codecs are tested with two different encoding configs to determine exactly how the different options effect the performance: with transformation ([]) and without transformation ([native]).

Included test messages

Some of these messages are ripped from the call flow examples in an old version of the RFC and others are created to test a specific feature of megaco.

Measurement tool directory name

Be sure not no name the directory containing the measurement binaries starting with 'megaco-', e.g. megaco-meas. This will confuse the erlang application loader (erlang applications are named, e.g. megaco-5.2).

megaco

Main API of the Megaco application

Interface module for the Megaco application

Summary

Types

action_reply()

action_reps()

action_reqs()

action_request()

conn_handle()

conn_info_item()

This type is a basic (atom) lookup key (for info on an active connection). The corresponding value can be of any type.

counter()

counter_value()

digit_map_event()

digit_map_kind()

digit_map_letter()

digit_map_value()

error_desc()

global_counter()

megaco_message()

megaco_timer()

mid()

The Megaco Identifier.

property_group()

property_groups()

property_parm()

protocol_version()

receive_handle()

sdp()

sdp_property_group()

sdp_property_groups()

sdp_property_parm()

segment_no()

send_handle()

Opaque send handle whose contents is internal for the send module. May be any term.

system_info_item()

System info items.

trace_data()

The trace data passed to the trace handler fun (in the second argument) and returned by same. For instance this could be a file descriptor, that the trace handler fun can use to print the event to a file.

trace_event()

The trace event generated by dbg.

trace_handler()

The trace handler fun is used to "process" each trace event (for instance print to file or to stdout after formating).

trace_level()

How much trace events should be produced. min (=0) means no trace events are produced, which is the default.

transaction_id()

transaction_reply()

user_info_item()

void()

The type is used when a functions return is to be ignored.

Functions

call(ConnHandle, ActionRequests, SendOptions)

Sends one or more transaction request(s) and waits for the reply.

cancel(ConnHandle, CancelReason)

Cancel all outstanding messages for this connection

cast(ConnHandle, ActionRequests, SendOptions)

Sends one or more transaction request(s) but does NOT wait for a reply

conn_info(ConnHandle)

Equivalent to conn_info/2.

conn_info(ConnHandle, ConnInfo)

Lookup information about an active connection

connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid)

Equivalent to connect/5.

connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid, Extra)

Establish a "virtual" connection

decode_sdp(PP)

Decode (parse) a property parameter construct.

disable_trace()

This function is used to stop megaco tracing.

disconnect(ConnHandle, DiscoReason)

Tear down a "virtual" connection

enable_trace(Level, Destination)

This function is used to start megaco tracing at a given Level and direct result to the given Destination.

encode_actions(ConnHandle, ActionRequests, Options)

Encodes lists of action requests for one or more transaction request(s).

encode_sdp(SDP)

Encode (generate) an SDP construct.

eval_digit_map(DigitMap)

Equivalent to eval_digit_map/2.

eval_digit_map(DigitMap, Timers)

Collect digit map letters according to the digit map.

get_stats()

Retreive all (SNMP) statistic counters maintained by the megaco application.

get_stats(ConnHandleOrGCounter)

Retreive a (SNMP) (global) statistic counter maintained by the megaco application.

get_stats(ConnHandle, Counter)

Retreive a (SNMP) statistic counter maintained by the megaco application.

info()

This function produces a list of information about the megaco application. Such as users and their config, connections and their config, statistics and so on.

parse_digit_map(DigitMapBody)

Parses a digit map body

print_version_info()

Equivalent to print_version_info/1.

print_version_info(Versions)

Utility function to produce a formated printout of the versions info generated by the versions1 and versions2 functions.

process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg)

Equivalent to process_received_message/5.

process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra)

Process a received message

receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg)

Equivalent to receive_message/5.

receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra)

Process a received message

report_digit_event(DigitMapEvalPid, Events)

Send one or more events to the event collector process.

reset_stats()

Reset all (SNMP) statistics counters.

reset_stats(ConnHandleOrGCounter)

Reset the specified (SNMP) statistics counter.

set_trace(Level)

This function is used to change the megaco trace level.

start()

Starts the Megaco application

start_user(UserMid, Config)

Initial configuration of a user

stop()

Stops the Megaco application

stop_user(UserMid)

Delete the configuration of a user

system_info()

Equivalent to system_info/1.

system_info(Item)

Lookup system information.

test_digit_event(DigitMap, Events)

Feed digit map collector with events and return the result

test_reply(ConnHandle, Version, EncodingMod, EncodingConfig, Reply)

Tests if the Reply argument is correctly composed.

test_request(ConnHandle, Version, EncodingMod, EncodingConfig, ActionRequests)

Tests if the Actions argument is correctly composed.

token_tag2string(Tag)

Equivalent to token_tag2string/3.

token_tag2string(Tag, EncodingMod)

Equivalent to token_tag2string/3.

token_tag2string(Tag, EncodingMod, Version)

Convert a token tag to a string

update_conn_info(ConnHandle, Item, Value)

Update information about an active connection

update_user_info(UserMid, Item, Value)

Update information about a user

user_info(UserMid)

Equivalent to user_info/2.

user_info(UserMid, Input)

Lookup user information

versions1()

Equivalent to versions2/0.

versions2()

Utility functions used to retrieve some system and application info.

Types

action_reply()

-type action_reply() :: megaco_encoder:action_reply().

action_reps()

(not exported)

-type action_reps() :: [action_reply()].

action_reqs()

(not exported)

-type action_reqs() :: binary() | [action_request()].

action_request()

-type action_request() :: megaco_encoder:action_request().

conn_handle()

-type conn_handle() :: megaco_user:conn_handle().

conn_info_item()

(not exported)

-type conn_info_item() ::
          control_pid | send_handle | local_mid | remote_mid | receive_handle | trans_id |
          max_trans_id | request_timer | long_request_timer | request_keep_alive_timeout |
          long_request_resend | reply_timer | call_proxy_gc_timeout | auto_ack | trans_ack |
          trans_ack_maxcount | trans_req | trans_req_maxcount | trans_req_maxsize | trans_timer |
          pending_timer | sent_pending_limit | recv_pending_limit | send_mod | encoding_mod |
          encoding_config | protocol_version | strict_version | reply_data | threaded |
          resend_indication | segment_reply_ind | segment_recv_timer | segment_send | max_pdu_size.

This type is a basic (atom) lookup key (for info on an active connection). The corresponding value can be of any type.

control_pid - The process identifier of the controlling process for a connection.

Value type: pid()

send_handle - Opaque send handle whose contents is internal for the send module.

Value type: send_handle/0

local_mid - The local mid (of the connection, i.e. the own mid).

Value type: mid/0

remote_mid - The remote mid (of the connection).

Value type: mid/0

receive_handle - Construct a megaco_receive_handle record.

Value type: receive_handle/0

trans_id - Next transaction id.

Note that transaction id's are (currently) maintained on a per user basis so there is no way to be sure that the value returned will actually be used for a transaction sent on this connection (in case a user has several connections, which is not at all unlikely).

Value type: transaction_id/0 | undefined_serial

max_trans_id - Last transaction id.

Value type: transaction_id/0 | infinity

request_timer - Wait for reply.

The timer is cancelled when a reply is received.

When a pending message is received, the timer is cancelled and the long_request_timer is started instead (see below). No resends will be performed from this point (since we now know that the other side has received the request).

When the timer reaches an intermediate expire, the request is resent and the timer is restarted.

When the timer reaches the final expire, either the function megaco:call will return with {error, timeout} or the callback function handle_trans_reply will be called with UserReply = {error, timeout} (if megaco:cast was used).

Value type: megaco_timer/0

Defaults to #megaco_incr_timer{}.

long_request_timer - Wait for reply after having received a pending message.

When the timer reaches an intermediate expire, the timer restarted.

When a pending message is received, and the long_request_timer is not "on its final leg", the timer will be restarted, and, if long_request_resend = true, the request will be re-sent.

Value type: megaco_timer/0

Defaults to 60 seconds.

request_keep_alive_timeout - Specifies the timeout time for the request-keep-alive timer.

This timer is started when the first reply to an asynchronous request (issued using the megaco:cast/3 function) arrives. As long as this timer is running, replies will be delivered via the handle_trans_reply/4,5 callback function, with their "arrival number" (see UserReply of the handle_trans_reply/4,5 callback function).

Replies arriving after the timer has expired, will be delivered using the handle_unexpected_trans/3,4 callback function.

Value type: plain | non_neg_integer()

Defaults to plain.

long_request_resend - This option indicates weather the request should be resent until the reply is received, even though a pending message has been received.

Normally, after a pending message has been received, the request is not resent (since a pending message is an indication that the request has been received). But since the reply (to the request) can be lost, this behaviour has its values.

It is of course pointless to set this value to true unless the long_request_timer (see above) is also set to an incremental timer (#megaco_incr_timer{}).

Value type: boolean()

Defaults to false.

reply_timer - Wait for an ack.

When a request is received, some info related to the reply is store internally (e.g. the binary of the reply). This info will live until either an ack is received or this timer expires. For instance, if the same request is received again (e.g. a request with the same transaction id), the (stored) reply will be (re-) sent automatically by megaco.

If the timer is of type #megaco_incr_timer{}, then for each intermediate timout, the reply will be resent (this is valid until the ack is received or the timer expires).

Value type: megaco_timer/0

Defaults to 30000.

call_proxy_gc_timeout - Timeout time for the call proxy.

When a request is sent using the call/3 function, a proxy process is started to handle all replies. When the reply has been received and delivered to the user, the proxy process continue to exist for as long as this option specifies. Any received messages, is passed on to the user via the handle_unexpected_trans callback function.

The timeout time is in milliseconds. A value of 0 (zero) means that the proxy process will exit directly after the reply has been delivered.

Value type: non_neg_integer()

Defaults to 5000 (= 5 seconds).

auto_ack - Automatic send transaction ack when the transaction reply has been received (see trans_ack below).

This is used for three-way-handshake.

Value type: boolean()

Defaults to false.

trans_ack - Shall ack's be accumulated or not.

This property is only valid if auto_ack is true.

If auto_ack is true, then if trans_ack is false, ack's will be sent immediately. If trans_ack is true, then ack's will instead be sent to the transaction sender process for accumulation and later sending (see trans_ack_maxcount, trans_req_maxcount, trans_req_maxsize, trans_ack_maxcount and trans_timer).

See also transaction sender for more info.

Value type: boolean()

Defaults to false.

trans_ack_maxcount - Maximum number of accumulated ack's. At most this many ack's will be accumulated by the transaction sender (if started and configured to accumulate ack's).

See also transaction sender for more info.

Value type: non_neg_integer()

Defaults to 10.

trans_req - Shall requests be accumulated or not.

If trans_req is false, then request(s) will be sent immediately (in its own message).

If trans_req is true, then request(s) will instead be sent to the transaction sender process for accumulation and later sending (see trans_ack_maxcount, trans_req_maxcount, trans_req_maxsize, trans_ack_maxcount and trans_timer).

See also transaction sender for more info.

Value type: boolean()

Defaults to false.

trans_req_maxcount - Maximum number of accumulated requests. At most this many requests will be accumulated by the transaction sender (if started and configured to accumulate requests).

See also transaction sender for more info.

Value type: non_neg_integer()

Defaults to 10.

trans_req_maxsize - Maximum size of the accumulated requests. At most this much requests will be accumulated by the transaction sender (if started and configured to accumulate requests).

See also transaction sender for more info.

Value type: non_neg_integer()

Defaults to 2048.

trans_timer - Transaction sender timeout time. Has two functions. First, if the value is 0, then transactions will not be accumulated (e.g. the transaction sender process will not be started). Second, if the value is greater then 0 and auto_ack and trans_ack is true or if trans_req is true, then transaction sender will be started and transactions (which is depending on the values of auto_ack, trans_ack and trans_req) will be accumulated, for later sending.

See also transaction sender for more info.

Value type: non_neg_integer()

Defaults to 0.

pending_timer - Automatic send transaction pending if the timer expires before a transaction reply has been sent. This timer is also called provisional response timer.

Value type: megaco_timer/0

Defaults to 30000 (= 30 seconds).

sent_pending_limit - Sent pending limit (see the MGOriginatedPendingLimit and the MGCOriginatedPendingLimit of the megaco root package). This parameter specifies how many pending messages that can be sent (for a given received transaction request). When the limit is exceeded, the transaction is aborted (see handle_trans_request_abort) and an error message is sent to the other side.

Note that this has no effect on the actual sending of pending transactions. This is either implicit (e.g. when receiving a re-sent transaction request for a request which is being processed) or controlled by the pending_timer, see above.

Value type: pos_integer() | infinity

Defaults to infinity.

recv_pending_limit - Receive pending limit (see the MGOriginatedPendingLimit and the MGCOriginatedPendingLimit of the megaco root package). This parameter specifies how many pending messages that can be received (for a sent transaction request). When the limit is exceeded, the transaction is considered lost, and an error returned to the user (through the call-back function handle_trans_reply).

Value type: pos_integer() | infinity

Defaults to infinity.

send_mod - Send callback module which exports send_message/2. The function SendMod:send_message(SendHandle, Binary) is invoked when the bytes needs to be transmitted to the remote user.

Value type: module().

Defaults to megaco_tcp.

encoding_mod - Encoding callback module which exports encode_message/2 and decode_message/2. The function EncodingMod:encode_message(EncodingConfig, MegacoMessage) is invoked whenever a 'MegacoMessage' record needs to be translated into an Erlang binary. The function EncodingMod:decode_message(EncodingConfig, Binary) is invoked whenever an Erlang binary needs to be translated into a 'MegacoMessage' record.

Value type: module().

Defaults to megaco_pretty_text_encoder.

encoding_config - Encoding module config.

Value type: loist().

Defaults to [].

protocol_version - Actual protocol version.

Value type: protocol_version/0

Defaults to 1.

strict_version - Strict version control, i.e. when a message is received, verify that the version is that which was negotiated.

Value type: boolean()

Defaults to true.

reply_data - Default reply data.

Value type: term()

Defaults to undefined.

threaded - If a received message contains several transaction requests, this option indicates whether the requests should be handled sequentially in the same process (false), or if each request should be handled by its own process (true i.e. a separate process is spawned for each request).

Value type: boolean()

Defaults to false.

resend_indication - This option indicates weather the transport module should be told if a message send is a resend or not.

If false, megaco messages are sent using the send_message/2 function.

If true, megaco message re-sends are made using the resend_message function. The initial message send is still done using the send_message function.

The special value flag instead indicates that the function send_message/3 shall be used.

Value type: flag | boolean()

Defaults to false.

segment_reply_ind - This option specifies if the user shall be notified of received segment replies or not.

See handle_segment_reply callback function for more information.

Value type: boolean()

Defaults to false.

segment_recv_timer - This timer is started when the segment indicated by the segmentation complete token (e.g. the last of the segment which makes up the reply) is received, but all segments has not yet been received.

When the timer finally expires, a "megaco segments not received" (459) error message is sent to the other side and the user is notified with a segment timeout UserReply in either the handle_trans_reply callback function or the return value of the call/2 function.

Value type: megaco_timer/0

Defaults to 10000 (= 10 seconds).

segment_send - Shall outgoing messages be segmented or not.

Value type: none | pos_integer() | infinity

none - Do not segment outgoing reply messages. This is useful when either it is known that messages are never to large or that the transport protocol can handle such things on its own (e.g. TCP or SCTP).

pos_integer/0 - Outgoing reply messages will be segmented as needed (see max_pdu_size below). This value, K, indicate the outstanding window, i.e. how many segments can be outstanding (not acknowledged) at any given time.

infinity - Outgoing reply messages will be segmented as needed (see max_pdu_size below). Segment messages are sent all at once (i.e. no acknowledgement awaited before sending the next segment).

Defaults to none.

max_pdu_size - Max message size. If the encoded message (PDU) exceeds this size, the message should be segmented, and then encoded.

Value type: infinity | pos_integer()

Defaults to infinity.

counter()

(not exported)

-type counter() :: medGwyGatewayNumTimerRecovery | medGwyGatewayNumErrors.

counter_value()

(not exported)

-type counter_value() :: non_neg_integer().

digit_map_event()

-type digit_map_event() :: megaco_digit_map:event().

digit_map_kind()

-type digit_map_kind() :: megaco_digit_map:kind().

digit_map_letter()

-type digit_map_letter() :: megaco_digit_map:letter().

digit_map_value()

-type digit_map_value() :: megaco_digit_map:value().

error_desc()

-type error_desc() :: megaco_encoder:error_desc().

global_counter()

(not exported)

-type global_counter() :: medGwyGatewayNumErrors.

megaco_message()

(not exported)

-type megaco_message() :: megaco_encoder:megaco_message().

megaco_timer()

(not exported)

-type megaco_timer() :: megaco_user:megaco_timer().

mid()

-type mid() ::
          {ip4Address, megaco_encoder:ip4Address()} |
          {ip6Address, megaco_encoder:ip6Address()} |
          {domainName, megaco_encoder:domainName()} |
          {deviceName, megaco_encoder:deviceName()} |
          {mtpAddress, megaco_encoder:mtpAddress()}.

The Megaco Identifier.

property_group()

-type property_group() :: megaco_sdp:property_group().

property_groups()

-type property_groups() :: megaco_sdp:property_groups().

property_parm()

-type property_parm() :: megaco_sdp:property_parm().

protocol_version()

-type protocol_version() :: megaco_encoder:protocol_version().

receive_handle()

-type receive_handle() :: megaco_user:receive_handle().

sdp()

-type sdp() :: megaco_sdp:sdp().

sdp_property_group()

(not exported)

-type sdp_property_group() :: megaco_sdp:sdp_property_group().

sdp_property_groups()

(not exported)

-type sdp_property_groups() :: megaco_sdp:sdp_property_groups().

sdp_property_parm()

(not exported)

-type sdp_property_parm() :: megaco_sdp:sdp_property_parm().

segment_no()

(not exported)

-type segment_no() :: megaco_encoder:segment_no().

send_handle()

(not exported)

-type send_handle() :: term().

Opaque send handle whose contents is internal for the send module. May be any term.

system_info_item()

(not exported)

-type system_info_item() ::
          text_config | connections | users | n_active_requests | n_active_replies |
          n_active_connections | reply_counters | pending_counters.

System info items.

text_config - The text encoding config.

Value type: term()

connections - Lists all active connections. Returns a list of megaco_conn_handle records.

Value type: [conn_handle/0]

users - Lists all active users.

Value type: [mid/0]

n_active_requests - Returns number of requests that has originated from this Erlang node and still are active (and therefore consumes system resources).

Value type: non_neg_integer()

n_active_replies - Returns the number of replies that has originated from this Erlang node and still are active (and therefore consumes system resources).

Value type: non_neg_integer()

n_active_connections - Returns the number of active connections.

Value type: non_neg_integer()

reply_counters - Returns a list of the reply counters.

Value type: [{conn_handle/0, transaction_id/0, non_neg_integer()}]

pending_counters - Returns a list of the receive and sent pending counters.

Value type: [{recv | sent, [{transaction_id/0, non_neg_integer()}]}]

trace_data()

(not exported)

-type trace_data() :: term().

The trace data passed to the trace handler fun (in the second argument) and returned by same. For instance this could be a file descriptor, that the trace handler fun can use to print the event to a file.

trace_event()

(not exported)

-type trace_event() :: term().

The trace event generated by dbg.

trace_handler()

(not exported)

-type trace_handler() :: fun((trace_event(), trace_data()) -> trace_data()).

The trace handler fun is used to "process" each trace event (for instance print to file or to stdout after formating).

trace_level()

-type trace_level() :: min | max | 0..100.

How much trace events should be produced. min (=0) means no trace events are produced, which is the default.

transaction_id()

(not exported)

-type transaction_id() :: pos_integer().

transaction_reply()

-type transaction_reply() :: megaco_encoder:transaction_reply().

user_info_item()

(not exported)

-type user_info_item() ::
          connections | receive_handle | trans_id | min_trans_id | max_trans_id | request_timer |
          long_request_timer | long_request_resend | reply_timer | request_keep_alive_timeout |
          call_proxy_gc_timeout | auto_ack | trans_ack | trans_ack_maxcount | trans_req |
          trans_req_maxcount | trans_req_maxsize | trans_timer | pending_timer | sent_pending_limit |
          recv_pending_limit | send_mod | encoding_mod | encoding_config | protocol_version |
          strict_version | reply_data | user_mod | user_args | threaded | resend_indication |
          segment_reply_ind | segment_recv_timer | segment_send | max_pdu_size.

connections - Lists all active connections for this user. Returns a list of megaco_conn_handle records.

Value type: [conn_handle/0]

receive_handle - Construct a receive_handle from user config.

Value type: receive_handle/0

trans_id - Current transaction id.

Value type: transaction_id/0 | undefined_serial

min_trans_id - First transaction id.

Value type: transaction_id/0

Defaults to 1.

max_trans_id - Last transaction id.

Value type: transaction_id/0 | infinity

Defaults to infinity.

request_timer - Wait for reply.

The timer is cancelled when a reply is received.

When a pending message is received, the timer is cancelled and the long_request_timer is started instead (see below). No resends will be performed from this point (since we now know that the other side has received the request).

When the timer reaches an intermediate expire, the request is resent and the timer is restarted.

When the timer reaches the final expire, either the function megaco:call will return with {error, timeout} or the callback function handle_trans_reply will be called with UserReply = {error, timeout} (if megaco:cast was used).

Value type: megaco_timer/0

Defaults to #megaco_incr_timer{}.

long_request_timer - Wait for reply after having received a pending message.

When the timer reaches an intermediate expire, the timer is restarted.

When a pending message is received, and the long_request_timer is not "on its final leg", the timer will be restarted, and, if long_request_resend = true, the request will be re-sent.

Value type: megaco_timer/0

Defaults to 60000 (= 60 seconds).

long_request_resend - This option indicates weather the request should be resent until the reply is received, even though a pending message has been received.

Normally, after a pending message has been received, the request is not resent (since a pending message is an indication that the request has been received). But since the reply (to the request) can be lost, this behaviour has its values.

It is of course pointless to set this value to true unless the long_request_timer (see above) is also set to an incremental timer (#megaco_incr_timer{}).

Value type: boolean()

Defaults to false.

reply_timer - Wait for an ack.

When a request is received, some info related to the reply is store internally (e.g. the binary of the reply). This info will live until either an ack is received or this timer expires. For instance, if the same request is received again (e.g. a request with the same transaction id), the (stored) reply will be (re-) sent automatically by megaco.

If the timer is of type #megaco_incr_timer{}, then for each intermediate timout, the reply will be resent (this is valid until the ack is received or the timer expires).

Value type: megaco_timer/0

Defaults to 30 seconds.

request_keep_alive_timeout - Specifies the timeout time for the request-keep-alive timer.

This timer is started when the first reply to an asynchronous request (issued using the megaco:cast/3 function) arrives. As long as this timer is running, replies will be delivered via the handle_trans_reply/4,5 callback function, with their "arrival number" (see UserReply of the handle_trans_reply/4,5 callback function).

Replies arriving after the timer has expired, will be delivered using the handle_unexpected_trans/3,4 callback function.

Value type: plain | non_neg_integer()

Defaults to plain.

call_proxy_gc_timeout - Timeout time for the call proxy.

When a request is sent using the call/3 function, a proxy process is started to handle all replies. When the reply has been received and delivered to the user, the proxy process continue to exist for as long as this option specifies. Any received messages, is passed on to the user via the handle_unexpected_trans callback function.

The timeout time is in milliseconds. A value of 0 (zero) means that the proxy process will exit directly after the reply has been delivered.

Value type: pos_integer()

Defaults to 5000 (= 5 seconds).

auto_ack - Automatic send transaction ack when the transaction reply has been received (see trans_ack below).

This is used for three-way-handshake.

Value type: boolean()

Defaults to false.

trans_ack - Shall ack's be accumulated or not.

This property is only valid if auto_ack is true.

If auto_ack is true, then if trans_ack is false, ack's will be sent immediately. If trans_ack is true, then ack's will instead be sent to the transaction sender process for accumulation and later sending (see trans_ack_maxcount, trans_req_maxcount, trans_req_maxsize, trans_ack_maxcount and trans_timer).

See also transaction sender for more info.

Value type: boolean()

Defaults to false.

trans_ack_maxcount - Maximum number of accumulated ack's. At most this many ack's will be accumulated by the transaction sender (if started and configured to accumulate ack's).

See also transaction sender for more info.

Value type: integer()

Defaults to 10.

trans_req - Shall requests be accumulated or not.

If trans_req is false, then request(s) will be sent immediately (in its own message).

If trans_req is true, then request(s) will instead be sent to the transaction sender process for accumulation and later sending (see trans_ack_maxcount, trans_req_maxcount, trans_req_maxsize, trans_ack_maxcount and trans_timer).

See also transaction sender for more info.

Value type: boolean()

Defaults to false.

trans_req_maxcount - Maximum number of accumulated requests. At most this many requests will be accumulated by the transaction sender (if started and configured to accumulate requests).

See also transaction sender for more info.

Value type: integer()

Defaults to 10.

trans_req_maxsize - Maximum size of the accumulated requests. At most this much requests will be accumulated by the transaction sender (if started and configured to accumulate requests).

See also transaction sender for more info.

Value type: integer()

Defaults to 2048.

trans_timer - Transaction sender timeout time. Has two functions. First, if the value is 0, then transactions will not be accumulated (e.g. the transaction sender process will not be started). Second, if the value is greater then 0 and auto_ack and trans_ack are both true or if trans_req is true, then transaction sender will be started and transactions (which is depending on the values of auto_ack, trans_ack and trans_req) will be accumulated, for later sending.

See also transaction sender for more info.

Value type: integer()

Defaults to 0.

pending_timer - Automatically send pending if the timer expires before a transaction reply has been sent. This timer is also called provisional response timer.

Value type: megaco_timer/0

Defaults to 30000.

sent_pending_limit - Sent pending limit (see the MGOriginatedPendingLimit and the MGCOriginatedPendingLimit of the megaco root package). This parameter specifies how many pending messages that can be sent (for a given received transaction request). When the limit is exceeded, the transaction is aborted (see handle_trans_request_abort) and an error message is sent to the other side.

Note that this has no effect on the actual sending of pending transactions. This is either implicit (e.g. when receiving a re-sent transaction request for a request which is being processed) or controlled by the pending_timer, see above.

Value type: infinity | pos_integer()

Defaults to infinity.

recv_pending_limit - Receive pending limit (see the MGOriginatedPendingLimit and the MGCOriginatedPendingLimit of the megaco root package). This parameter specifies how many pending messages that can be received (for a sent transaction request). When the limit is exceeded, the transaction is considered lost, and an error returned to the user (through the call-back function handle_trans_reply).

Value type: infinity | pos_integer()

Defaults to infinity.

send_mod - Send callback module which exports send_message/2. The function SendMod:send_message(SendHandle, Binary) is invoked when the bytes needs to be transmitted to the remote user.

Value type: module()

Defaults to megaco_tcp.

encoding_mod - Encoding callback module which exports encode_message/2 and decode_message/2. The function EncodingMod:encode_message(EncodingConfig, MegacoMessage) is invoked whenever a 'MegacoMessage' record needs to be translated into an Erlang binary. The function EncodingMod:decode_message(EncodingConfig, Binary) is invoked whenever an Erlang binary needs to be translated into a 'MegacoMessage' record.

Value type: module()

Defaults to megaco_pretty_text_encoder.

encoding_config - Encoding module config.

Value type: list()

Defaults to [].

protocol_version - Actual protocol version.

Value type: protocol_version/0

Defaults to 1.

strict_version - Strict version control, i.e. when a message is received, verify that the version is that which was negotiated.

Value type: boolean()

Defaults to true.

reply_data - Default reply data.

Value type: term()

Defaults to undefined.

user_mod - Name of the user callback module. See the the reference manual for megaco_user for more info.

Value type: module()

Has no default value since its an mandatory config option.

user_args - List of extra arguments to the user callback functions. See the the reference manual for megaco_user for more info.

Value type: list()

threaded - If a received message contains several transaction requests, this option indicates whether the requests should be handled sequentially in the same process (false), or if each request should be handled by its own process (true i.e. a separate process is spawned for each request).

Value type: boolean()

Defaults to false.

resend_indication - This option indicates weather the transport module should be told if a message send is a resend or not.

If false, megaco messages are sent using the send_message function.

If true, megaco message re-sends are made using the resend_message function. The initial message send is still done using the send_message function.

The special value flag instead indicates that the function send_message/3 shall be used.

Value type: boolean()

Defaults to false.

segment_reply_ind - This option specifies if the user shall be notified of received segment replies or not.

See handle_segment_reply callback function for more information.

Value type: boolean()

Defaults to false.

segment_recv_timer - This timer is started when the segment indicated by the segmentation complete token is received, but all segments has not yet been received.

When the timer finally expires, a "megaco segments not received" (459) error message is sent to the other side and the user is notified with a segment timeout UserReply in either the handle_trans_reply callback function or the return value of the call/3 function.

Value type: megaco_timer/0

Defaults to 10000.

segment_send - Shall outgoing messages be segmented or not.

Value type: none | pos_integer() | infinity

none - Do not segment outgoing reply messages. This is useful when either it is known that messages are never to large or that the transport protocol can handle such things on its own (e.g. TCP or SCTP).

pos_integer/0 - Outgoing reply messages will be segmented as needed (see max_pdu_size below). This value, K, indicate the outstanding window, i.e. how many segments can be outstanding (not acknowledged) at any given time.

infinity - Outgoing reply messages will be segmented as needed (see max_pdu_size below). Segment messages are sent all at once (i.e. no acknowledgement awaited before sending the next segment).

Defaults to none.

max_pdu_size - Max message size. If the encoded message (PDU) exceeds this size, the message should be segmented, and then encoded.

Value type: infinity | pos_integer()

Defaults to infinity.

void()

-type void() :: term().

The type is used when a functions return is to be ignored.

Functions

call(ConnHandle, ActionRequests, SendOptions)

-spec call(ConnHandle, ActionRequests, SendOptions) -> {ProtocolVersion, UserReply | [UserReply]}
              when
                  ConnHandle :: conn_handle(),
                  ActionRequests :: action_reqs() | [action_reqs()],
                  SendOptions :: [SendOption],
                  SendOption ::
                      {request_timer, megaco_timer()} |
                      {long_request_timer, megaco_timer()} |
                      {send_handle, send_handle()} |
                      {protocol_version, protocol_version()} |
                      {call_proxy_gc_timeout, non_neg_integer()},
                  ProtocolVersion :: protocol_version(),
                  UserReply :: Success | Failure,
                  Success :: {ok, Result} | {ok, Result, SuccessExtra},
                  Result :: MessageResult | SegmentResult,
                  MessageResult :: action_reps(),
                  SegmentResult :: SegmentsOk,
                  SegmentsOk :: [{segment_no(), action_reps()}],
                  Failure :: {error, Reason} | {error, Reason, ErrorExtra},
                  Reason :: MessageReason | SegmentReason | UserCancelReason | SendReason | OtherReason,
                  MessageReason :: error_desc(),
                  SegmentReason ::
                      {segment, SegmentsOk, SegmentsErr} |
                      {segment_timeout, MissingSegments, SegmentsOk, SegmentsErr},
                  SegmentsErr :: {segment_no(), error_desc()},
                  MissingSegments :: [segment_no()],
                  UserCancelReason :: {user_cancel, ReasonForUserCancel},
                  ReasonForUserCancel :: term(),
                  SendReason :: SendCancelledReason | SendFailedReason,
                  SendCancelledReason :: {send_message_cancelled, term()},
                  SendFailedReason :: {send_message_failed, term()},
                  OtherReason ::
                      {wrong_mid, WrongMid :: mid(), RightMid :: mid(), transaction_reply()} | term(),
                  SuccessExtra :: term(),
                  ErrorExtra :: term().

Sends one or more transaction request(s) and waits for the reply.

When sending one transaction in a message, ActionRequests should be action_reqs/0 (the reply will then be UserReply). When sending several transactions in a message, ActionRequests should be [action_reqs()] (the reply will then be [UserReply]). Each element of the list is part of one transaction.

For some of our codecs (not binary), it is also possible to pre-encode the actions, in which case ActionRequests will be either a binary/0 or [binary()].

The function returns when the reply arrives, when the request timer eventually times out or when the outstanding requests are explicitly cancelled.

The default values of the send options are obtained by megaco:conn_info(ConnHandle, Item). But the send options above, may explicitly be overridden.

The ProtocolVersion version is the version actually encoded in the reply message.

At Success, the UserReply contains a list of 'ActionReply' records possibly containing error indications.

A Failure, indicates that the remote user has replied with an explicit transactionError.

A UserCancelReason, indicates that the request has been canceled by the user. ReasonForUserCancel is the reason given in the call to the cancel/2 function.

A send error (SendReason), indicates that the send function of the megaco transport callback module failed to send the request. There are two separate cases: SendCancelledReason and SendFailedReason. The first is the result of the send function returning {cancel, Reason} and the second is some other kind of erroneous return value. See the send_message function for more info.

An OtherReason, indicates some other error such as timeout.

For more info about the 'extra' part of the result (SuccessExtra and ErrorExtra), see the note in the user callback module documentation.

cancel(ConnHandle, CancelReason)

-spec cancel(ConnHandle, CancelReason) -> ok | {error, Reason}
                when ConnHandle :: conn_handle(), CancelReason :: term(), Reason :: term().

Cancel all outstanding messages for this connection

This causes outstanding megaco:call/3 requests to return. The callback functions UserMod:handle_reply/4 and UserMod:handle_trans_ack/4 are also invoked where it applies. See the megaco_user module for more info about the callback arguments.

cast(ConnHandle, ActionRequests, SendOptions)

-spec cast(ConnHandle, ActionRequests, SendOptions) -> ok | {error, Reason}
              when
                  ConnHandle :: conn_handle(),
                  ActionRequests :: action_reqs() | [action_reqs()],
                  SendOptions :: [SendOption],
                  SendOption ::
                      {request_keep_alive_timeout, RequestKeepAliveTimer} |
                      {request_timer, megaco_timer()} |
                      {long_request_timer, megaco_timer()} |
                      {send_handle, send_handle()} |
                      {reply_data, ReplyData} |
                      {protocol_version, ProtocolVersion},
                  RequestKeepAliveTimer :: plain | non_neg_integer(),
                  ReplyData :: term(),
                  ProtocolVersion :: protocol_version(),
                  Reason :: term().

Sends one or more transaction request(s) but does NOT wait for a reply

When sending one transaction in a message, ActionRequests should be action_reqs/0. When sending several transactions in a message, ActionRequests should be [action_reqs()]. Each element of the list is part of one transaction.

For some of our codecs (not binary), it is also possible to pre-encode the actions, in which case Actions will be either a binary/0 or [binary()].

The default values of the send options are obtained by megaco:conn_info(ConnHandle, Item). But the send options above, may explicitly be overridden.

The ProtocolVersion version is the version actually encoded in the reply message.

The callback function UserMod:handle_trans_reply/4 is invoked when the reply arrives, when the request timer eventually times out or when the outstanding requests are explicitly cancelled. See the megaco_user module for more info about the callback arguments.

Given as ReplyData argument to UserMod:handle_trans_reply/4.

conn_info(ConnHandle)

-spec conn_info(ConnHandle) -> [{Item, Value}]
                   when
                       ConnHandle :: conn_handle(),
                       Item :: requests | replies | conn_info_item(),
                       Value :: term().

Equivalent to conn_info/2.

conn_info(ConnHandle, ConnInfo)

-spec conn_info(ConnHandle, ConnInfo) -> Value
                   when
                       ConnHandle :: conn_handle(),
                       ConnInfo :: all | requests | replies | conn_info_item(),
                       Value :: term().

Lookup information about an active connection

Requires that the connection is active.

Failure: exit if, for instance, ConnHandle refers to a connection that no longer exists.

connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid)

-spec connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid) -> {ok, ConnHandle} | {error, Reason}
                 when
                     ReceiveHandle :: receive_handle(),
                     RemoteMid :: preliminary_mid | mid(),
                     SendHandle :: send_handle(),
                     ControlPid :: pid(),
                     ConnHandle :: conn_handle(),
                     Reason :: ConnectReason | HandleConnectReason | term(),
                     ConnectReason ::
                         {no_such_user, LocalMid} | {already_connected, ConnHandle} | term(),
                     LocalMid :: mid(),
                     HandleConnectReason :: {connection_refused, ConnData, ErrorInfo} | term(),
                     ConnData :: term(),
                     ErrorInfo :: term().

Equivalent to connect/5.

connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid, Extra)

-spec connect(ReceiveHandle, RemoteMid, SendHandle, ControlPid, Extra) ->
                 {ok, ConnHandle} | {error, Reason}
                 when
                     ReceiveHandle :: receive_handle(),
                     RemoteMid :: preliminary_mid | mid(),
                     SendHandle :: send_handle(),
                     ControlPid :: pid(),
                     Extra :: term(),
                     ConnHandle :: conn_handle(),
                     Reason :: ConnectReason | HandleConnectReason | term(),
                     ConnectReason ::
                         {no_such_user, LocalMid} | {already_connected, ConnHandle} | term(),
                     LocalMid :: mid(),
                     HandleConnectReason :: {connection_refused, ConnData, ErrorInfo} | term(),
                     ConnData :: term(),
                     ErrorInfo :: term().

Establish a "virtual" connection

Activates a connection to a remote user. When this is done the connection can be used to send messages (with SendMod:send_message/2). The ControlPid is the identifier of a process that controls the connection. That process will be supervised and if it dies, this will be detected and the UserMod:handle_disconnect/2 callback function will be invoked. See the megaco_user module for more info about the callback arguments. The connection may also explicitly be deactivated by invoking megaco:disconnect/2.

The ControlPid may be the identity of a process residing on another Erlang node. This is useful when you want to distribute a user over several Erlang nodes. In such a case one of the nodes has the physical connection. When a user residing on one of the other nodes needs to send a request (with megaco:call/3 or megaco:cast/3), the message will encoded on the originating Erlang node, and then be forwarded to the node with the physical connection. When the reply arrives, it will be forwarded back to the originator. The distributed connection may explicitly be deactivated by a local call to megaco:disconnect/2 or implicitly when the physical connection is deactivated (with megaco:disconnect/2, killing the controlling process, halting the other node, ...).

The call of this function will trigger the callback function UserMod:handle_connect/2 to be invoked. See the megaco_user module for more info about the callback arguments.

A connection may be established in several ways:

provisioned MID - The MG may explicitly invoke megaco:connect/4 and use a provisioned MID of the MGC as the RemoteMid.

upgrade preliminary MID - The MG may explicitly invoke megaco:connect/4 with the atom 'preliminary_mid' as a temporary MID of the MGC, send an intial message, the Service Change Request, to the MGC and then wait for an initial message, the Service Change Reply. When the reply arrives, the Megaco application will pick the MID of the MGC from the message header and automatically upgrade the connection to be a "normal" connection. By using this method of establishing the connection, the callback function UserMod:handle_connect/2 to be invoked twice. First with a ConnHandle with the remote_mid-field set to preliminary_mid, and then when the connection upgrade is done with the remote_mid-field set to the actual MID of the MGC.

automatic - When the MGC receives its first message, the Service Change Request, the Megaco application will automatically establish the connection by using the MG MID found in the message header as remote mid.

distributed - When a user (MG/MGC) is distributed over several nodes, it is required that the node hosting the connection already has activated the connection and that it is in the "normal" state. The RemoteMid must be a real Megaco MID and not a preliminary_mid.

An initial megaco_receive_handle record may be obtained with megaco:user_info(UserMid, receive_handle)

The send handle is provided by the preferred transport module, e.g. megaco_tcp, megaco_udp. Read the documentation about each transport module about the details.

The connect is done in two steps: first an internal connection setup and then by calling the user handle_connect callback function. The first step could result in an error with Reason = ConnectReason and the second an error with Reason = HandleConnectReason:

ConnectReason - An error with this reason is generated by the megaco application itself.

HandleConnectReason - An error with this reason is caused by the user handle_connect callback function either returning an error or an invalid value.

Extra can be any term/0 except the atom ignore_extra. It is passed (back) to the user via the callback function handle_connect/3.

decode_sdp(PP)

-spec decode_sdp(PP) -> {ok, SDP} | {error, Reason}
                    when
                        PP :: property_parm() | property_group() | property_groups() | asn1_NOVALUE,
                        SDP :: sdp() | DecodeSdpPropertyGroup | DecodeSdpPropertyGroups | asn1_NOVALUE,
                        DecodeSdpPropertyGroup :: [DecodeSDP],
                        DecodeSdpPropertyGroups :: [DecodeSdpPropertyGroup],
                        DecodeSDP :: sdp() | {property_parm(), DecodeError},
                        DecodeError :: term(),
                        Reason :: term().

Decode (parse) a property parameter construct.

When decoding property_group/0 or property_groups/0, those property parameter constructs that cannot be decoded (either because of decode error or because they are unknown), will be returned as a two-tuple. The first element of which will be the (undecoded) property parameter and the other the actual reason. This means that the caller of this function has to expect not only sdp-records, but also this two-tuple construct.

This function performs the following transformation:

property_parm() -> sdp()

property_group() -> sdp_property_group()

property_groups() -> sdp_property_groups()

disable_trace()

-spec disable_trace() -> void().

This function is used to stop megaco tracing.

disconnect(ConnHandle, DiscoReason)

-spec disconnect(ConnHandle, DiscoReason) -> ok | {error, ErrReason}
                    when ConnHandle :: conn_handle(), DiscoReason :: term(), ErrReason :: term().

Tear down a "virtual" connection

Causes the UserMod:handle_disconnect/2 callback function to be invoked. See the megaco_user module for more info about the callback arguments.

enable_trace(Level, Destination)

-spec enable_trace(Level, Destination) -> void()
                      when
                          Level :: trace_level(),
                          Destination :: File | Port | HandlerSpec | io,
                          File :: string(),
                          Port :: integer(),
                          HandlerSpec :: {HandlerFun, InitialData},
                          HandlerFun :: trace_handler(),
                          InitialData :: trace_data().

This function is used to start megaco tracing at a given Level and direct result to the given Destination.

It starts a tracer server and then sets the proper match spec (according to Level).

In the case when Destination is File, the printable megaco trace events will be printed to the file File using plain io:format/2.

In the case when Destination is io, the printable megaco trace events will be printed on stdout using plain io:format/2.

See dbg for further information.

encode_actions(ConnHandle, ActionRequests, Options)

-spec encode_actions(ConnHandle, ActionRequests, Options) -> {ok, Result} | {error, Reason}
                        when
                            ConnHandle :: conn_handle(),
                            ActionRequests :: action_reqs() | [action_reqs()],
                            Options :: [Option],
                            Option ::
                                {request_timer, megaco_timer()} |
                                {long_request_timer, megaco_timer()} |
                                {send_handle, send_handle()} |
                                {protocol_version, protocol_version()},
                            Result :: binary() | [binary()],
                            Reason :: term().

Encodes lists of action requests for one or more transaction request(s).

When encoding action requests for one transaction, Actions should be action_reqs/0. When encoding action requests for several transactions, Actions should be [action_reqs()]. Each element of the list is part of one transaction.

encode_sdp(SDP)

-spec encode_sdp(SDP) -> {ok, PP} | {error, Reason}
                    when
                        SDP ::
                            sdp_property_parm() |
                            sdp_property_group() |
                            sdp_property_groups() |
                            asn1_NOVALUE,
                        PP :: property_parm() | property_group() | property_groups() | asn1_NOVALUE,
                        Reason :: term().

Encode (generate) an SDP construct.

If a property_parm/0 is found as part of the input (SDP) then it is left unchanged.

This function performs the following transformation:

sdp() -> property_parm()

sdp_property_group() -> property_group()

sdp_property_groups() -> property_groups()

eval_digit_map(DigitMap)

-spec eval_digit_map(DigitMap) -> {ok, MatchResult} | {error, Reason}
                        when
                            DigitMap :: digit_map_value() | ParsedDigitMap,
                            ParsedDigitMap :: term(),
                            MatchResult :: {Kind, Letters} | {Kind, Letters, Extra},
                            Kind :: digit_map_kind(),
                            Letters :: [digit_map_letter()],
                            Extra :: digit_map_letter(),
                            Reason :: term().

Equivalent to eval_digit_map/2.

eval_digit_map(DigitMap, Timers)

-spec eval_digit_map(DigitMap, Timers) -> {ok, MatchResult} | {error, Reason}
                        when
                            DigitMap :: digit_map_value() | ParsedDigitMap,
                            ParsedDigitMap :: term(),
                            Timers :: Ignore | Reject,
                            Ignore :: ignore | {ignore, digit_map_value()},
                            Reject :: reject | {reject, digit_map_value()} | digit_map_value(),
                            MatchResult :: {Kind, Letters} | {Kind, Letters, Extra},
                            Kind :: digit_map_kind(),
                            Letters :: [digit_map_letter()],
                            Extra :: digit_map_letter(),
                            Reason :: term().

Collect digit map letters according to the digit map.

When evaluating a digit map, a state machine waits for timeouts and letters reported by megaco:report_digit_event/2. The length of the various timeouts are defined in the digit_map_value() record.

When a complete sequence of valid events has been received, the result is returned as a list of letters.

There are two options for handling syntax errors (that is when an unexpected event is received when the digit map evaluator is expecting some other event). The unexpected events may either be ignored or rejected. The latter means that the evaluation is aborted and an error is returned.

get_stats()

-spec get_stats() -> {ok, [TotalStats]} | {error, Reason}
                   when
                       TotalStats :: {conn_handle(), [Stats]} | {global_counter(), counter_value()},
                       Stats :: {counter(), counter_value()},
                       Reason :: term().

Retreive all (SNMP) statistic counters maintained by the megaco application.

The global counters handle events that cannot be attributed to a single connection (e.g. protocol errors that occur before the connection has been properly setup).

get_stats(ConnHandleOrGCounter)

-spec get_stats(GCounter) -> {ok, Value} | {error, Reason}
                   when GCounter :: global_counter(), Value :: counter_value(), Reason :: term();
               (ConnHandle) -> {ok, [Stats]} | {error, Reason}
                   when
                       ConnHandle :: conn_handle(),
                       Stats :: {counter(), counter_value()},
                       Reason :: term().

Retreive a (SNMP) (global) statistic counter maintained by the megaco application.

The global counters handle events that cannot be attributed to a single connection (e.g. protocol errors that occur before the connection has been properly setup).

Retreive all (SNMP) statistic counters maintained by the megaco application, for a specific connection.

get_stats(ConnHandle, Counter)

-spec get_stats(ConnHandle, Counter) -> {ok, Value} | {error, Reason}
                   when
                       ConnHandle :: conn_handle(),
                       Counter :: counter(),
                       Value :: counter_value(),
                       Reason :: term().

Retreive a (SNMP) statistic counter maintained by the megaco application.

info()

-spec info() -> Info when Info :: [{Key, Value}], Key :: atom(), Value :: term().

This function produces a list of information about the megaco application. Such as users and their config, connections and their config, statistics and so on.

This information can be produced by the functions user_info/2, conn_info/2, system_info/1 and get_stats/2 but this is a simple way to get it all at once.

parse_digit_map(DigitMapBody)

-spec parse_digit_map(DigitMapBody) -> {ok, ParsedDigitMap} | {error, Reason}
                         when DigitMapBody :: string(), ParsedDigitMap :: term(), Reason :: term().

Parses a digit map body

Parses a digit map body, represented as a list of characters, into a list of state transitions suited to be evaluated by megaco:eval_digit_map/1,2.

print_version_info()

-spec print_version_info() -> void().

Equivalent to print_version_info/1.

print_version_info(Versions)

-spec print_version_info(Versions) -> void() when Versions :: [VersionInfo], VersionInfo :: term().

Utility function to produce a formated printout of the versions info generated by the versions1 and versions2 functions.

The function print_version_info/0 uses the result of function version1/0 as VersionInfo.

Example:

           {ok, V} = megaco:versions1(), megaco:format_versions(V).

process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg)

-spec process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg) -> ok
                                  when
                                      ReceiveHandle :: receive_handle(),
                                      ControlPid :: pid(),
                                      SendHandle :: send_handle(),
                                      BinMsg :: binary().

Equivalent to process_received_message/5.

process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra)

-spec process_received_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra) -> ok
                                  when
                                      ReceiveHandle :: receive_handle(),
                                      ControlPid :: pid(),
                                      SendHandle :: send_handle(),
                                      BinMsg :: binary(),
                                      Extra :: term().

Process a received message

This function is intended to be invoked by some transport modules when get an incoming message. Which transport that actually is used is up to the user to choose.

The message is delivered as an Erlang binary and is decoded by the encoding module stated in the receive handle together with its encoding config (also in the receive handle). Depending of the outcome of the decoding various callback functions will be invoked. See megaco_user for more info about the callback arguments.

The argument Extra is just an opaque data structure passed to the user via the callback functions in the user callback module. Note however that if Extra has the value extra_undefined the argument will be ignored (same as if process_received_message/4 had been called). See the documentation for the behaviour of the callback module, megaco_user, for more info.

Note that all processing is done in the context of the calling process. A transport module could call this function via one of the spawn functions (e.g. spawn_opt). See also receive_message/4,5.

If the message cannot be decoded the following callback function will be invoked:

UserMod:handle_syntax_error/3

If the decoded message instead of transactions contains a message error, the following callback function will be invoked:

UserMod:handle_message_error/3

If the decoded message happens to be received before the connection is established, a new "virtual" connection is established. This is typically the case for the Media Gateway Controller (MGC) upon the first Service Change. When this occurs the following callback function will be invoked:

UserMod:handle_connect/2

For each transaction request in the decoded message the following callback function will be invoked:

UserMod:handle_trans_request/3

For each transaction reply in the decoded message the reply is returned to the user. Either the originating function megaco:call/3 will return. Or in case the originating function was megaco:case/3 the following callback function will be invoked:

UserMod:handle_trans_reply/4

When a transaction acknowledgement is received it is possible that user has decided not to bother about the acknowledgement. But in case the return value from UserMod:handle_trans_request/3 indicates that the acknowledgement is important the following callback function will be invoked:

UserMod:handle_trans_ack/4

See the megaco_user module for more info about the callback arguments.

receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg)

-spec receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg) -> ok
                         when
                             ReceiveHandle :: receive_handle(),
                             ControlPid :: pid(),
                             SendHandle :: send_handle(),
                             BinMsg :: binary().

Equivalent to receive_message/5.

receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra)

-spec receive_message(ReceiveHandle, ControlPid, SendHandle, BinMsg, Extra) -> ok
                         when
                             ReceiveHandle :: receive_handle(),
                             ControlPid :: pid(),
                             SendHandle :: send_handle(),
                             BinMsg :: binary(),
                             Extra :: term().

Process a received message

This is a callback function intended to be invoked by some transport modules when get an incoming message. Which transport that actually is used is up to the user to choose.

In principle, this function calls the process_received_message/4,5 function via a spawn to perform the actual processing.

report_digit_event(DigitMapEvalPid, Events)

-spec report_digit_event(DigitMapEvalPid, Events) -> ok | {error, Reason}
                            when
                                DigitMapEvalPid :: pid(),
                                Events :: digit_map_event() | [digit_map_event()],
                                Reason :: term().

Send one or more events to the event collector process.

Send one or more events to a process that is evaluating a digit map, that is a process that is executing megaco:eval_digit_map/1,2.

Note that the events $s | $S, l | $L and $z | $Z has nothing to do with the timers using the same characters.

reset_stats()

-spec reset_stats() -> void().

Reset all (SNMP) statistics counters.

reset_stats(ConnHandleOrGCounter)

-spec reset_stats(GCounter) -> void() when GCounter :: global_counter();
                 (ConnHandle) -> void() when ConnHandle :: conn_handle().

Reset the specified (SNMP) statistics counter.

Reset all (SNMP) statistics counters for a connection.

set_trace(Level)

-spec set_trace(Level) -> void() when Level :: trace_level().

This function is used to change the megaco trace level.

It is assumed that tracing has already been enabled (see enable_trace above).

start()

-spec start() -> ok | {error, Reason} when Reason :: term().

Starts the Megaco application

Users may either explicitly be registered with megaco:start_user/2 and/or be statically configured by setting the application environment variable 'users' to a list of {UserMid, Config} tuples. See the function megaco:start_user/2 for details.

start_user(UserMid, Config)

-spec start_user(UserMid, Config) -> ok | {error, Reason}
                    when
                        UserMid :: mid(),
                        Config :: [{Item, Value}],
                        Item :: user_info_item(),
                        Value :: term(),
                        Reason :: term().

Initial configuration of a user

Requires the megaco application to be started. A user is either a Media Gateway (MG) or a Media Gateway Controller (MGC). One Erlang node may host many users.

A user is identified by its UserMid, which must be a legal Megaco MID.

Config is a list of {Item, Value} tuples. See megaco:user_info/2 about which items and values that are valid.

stop()

-spec stop() -> ok | {error, Reason} when Reason :: term().

Stops the Megaco application

stop_user(UserMid)

-spec stop_user(UserMid) -> ok | {error, Reason} when UserMid :: mid(), Reason :: term().

Delete the configuration of a user

Requires that the user does not have any active connection.

system_info()

-spec system_info() -> [{Item, Value}] when Item :: system_info_item(), Value :: term().

Equivalent to system_info/1.

system_info(Item)

-spec system_info(Item) -> Value when Item :: system_info_item(), Value :: term().

Lookup system information.

test_digit_event(DigitMap, Events)

-spec test_digit_event(DigitMap, Events) -> {ok, Kind, Letters} | {error, Reason}
                          when
                              DigitMap :: digit_map_value() | ParsedDigitMap,
                              ParsedDigitMap :: term(),
                              Events :: digit_map_event() | [digit_map_event()],
                              Kind :: digit_map_kind(),
                              Letters :: [digit_map_letter()],
                              Reason :: term().

Feed digit map collector with events and return the result

This function starts the evaluation of a digit map with megaco:eval_digit_map/1 and sends a sequence of events to it with megaco:report_digit_event/2 in order to simplify testing of digit maps.

test_reply(ConnHandle, Version, EncodingMod, EncodingConfig, Reply)

-spec test_reply(ConnHandle, Version, EncodingMod, EncodingConfig, Reply) -> {MegaMsg, EncodeRes}
                    when
                        ConnHandle :: conn_handle(),
                        Version :: protocol_version(),
                        EncodingMod :: module(),
                        EncodingConfig :: list(),
                        Reply :: error_desc() | [action_reply()],
                        MegaMsg :: megaco_message(),
                        EncodeRes :: {ok, Bin} | {error, Reason},
                        Bin :: binary(),
                        Reason :: term().

Tests if the Reply argument is correctly composed.

This function is only intended for testing purposes. It's supposed to test the actual_reply() return value of the callback functions handle_trans_request and handle_trans_long_request functions (with the additions of the EncodingMod and EncodingConfig arguments). It composes a complete megaco message end attempts to encode it. The return value, will be a tuple of the composed megaco message and the encode result.

test_request(ConnHandle, Version, EncodingMod, EncodingConfig, ActionRequests)

-spec test_request(ConnHandle, Version, EncodingMod, EncodingConfig, ActionRequests) ->
                      {MegaMsg, EncodeRes}
                      when
                          ConnHandle :: conn_handle(),
                          Version :: protocol_version(),
                          EncodingMod :: module(),
                          EncodingConfig :: list(),
                          ActionRequests :: action_reqs() | [action_reqs()],
                          MegaMsg :: megaco_message(),
                          EncodeRes :: {ok, Bin} | {error, Reason},
                          Bin :: binary(),
                          Reason :: term().

Tests if the Actions argument is correctly composed.

This function is only intended for testing purposes. It's supposed to have a same kind of interface as the call/3 or cast/3 functions (with the additions of the EncodingMod and EncodingConfig arguments). It composes a complete megaco message end attempts to encode it. The return value, will be a tuple of the composed megaco message and the encode result.

token_tag2string(Tag)

-spec token_tag2string(Tag) -> Result
                          when Tag :: atom(), Result :: string() | {error, Reason}, Reason :: term().

Equivalent to token_tag2string/3.

token_tag2string(Tag, EncodingMod)

-spec token_tag2string(Tag, EncodingMod) -> Result
                          when
                              Tag :: atom(),
                              EncodingMod :: pretty | compact | module(),
                              Result :: string() | {error, Reason},
                              Reason :: term().

Equivalent to token_tag2string/3.

token_tag2string(Tag, EncodingMod, Version)

-spec token_tag2string(Tag, EncodingMod, Version) -> Result
                          when
                              Tag :: atom(),
                              EncodingMod :: pretty | compact | module(),
                              Version :: protocol_version() | v1 | v2 | v3,
                              Result :: string() | {error, Reason},
                              Reason :: term().

Convert a token tag to a string

If no encoder module is given, the default is used (which is pretty).

If no or an unknown version is given, the best version is used (which is v3).

If no match is found for Tag, Result will be the empty string ([]).

update_conn_info(ConnHandle, Item, Value)

-spec update_conn_info(ConnHandle, Item, Value) -> ok | {error, Reason}
                          when
                              ConnHandle :: conn_handle(),
                              Item :: conn_info_item(),
                              Value :: term(),
                              Reason :: term().

Update information about an active connection

Requires that the connection is activated. See conn_info_item/0 about which items and values that are valid.

update_user_info(UserMid, Item, Value)

-spec update_user_info(UserMid, Item, Value) -> ok | {error, Reason}
                          when
                              UserMid :: mid(),
                              Item :: user_info_item(),
                              Value :: term(),
                              Reason :: term().

Update information about a user

Requires that the user is started.

user_info(UserMid)

-spec user_info(UserMid) -> [{Item, Value}]
                   when UserMid :: mid(), Item :: requests | replies | user_info_item(), Value :: term().

Equivalent to user_info/2.

user_info(UserMid, Input)

-spec user_info(UserMid, Input) -> Result
                   when
                       Input :: Requests | Replies | Item,
                       Requests :: requests,
                       Replies :: replies,
                       Item :: user_info_item(),
                       UserMid :: mid(),
                       Conn :: conn_handle(),
                       Result :: RequestsResult | RepliesResult | ItemResult,
                       RequestsResult :: [{Conn, [TransId]}],
                       ItemResult :: term(),
                       RepliesResult :: [{Conn, [{TransId, ReplyState, Handler}]}],
                       TransId :: transaction_id(),
                       ReplyState :: prepare | eval_request | waiting_for_ack | aborted,
                       Handler :: undefined | pid().

Lookup user information

Lookup user information about currently active requests. Expected input type Input :: Requests with expected output type Result :: RequestsResult.

Lookup user information about currently active replies. Expected input type Input :: Replies with expected output type Result :: RepliesResult.

versions1()

-spec versions1() -> {ok, VersionInfo} | {error, Reason} when VersionInfo :: list(), Reason :: term().

Equivalent to versions2/0.

versions2()

-spec versions2() -> {ok, VersionInfo} | {error, Reason} when VersionInfo :: list(), Reason :: term().

Utility functions used to retrieve some system and application info.

The difference between the two functions is in how they get the modules to check. versions1 uses the app-file and versions2 uses the function application:get_key.

megaco_codec_meas

This module implements a simple megaco codec measurement tool.

Results are written to file (excel compatible text files) and on stdout.

Note that this module is not included in the runtime part of the application.

Summary

Functions

start()

Equivalent to start/1.

start(MessagePackage)

This function runs the measurement on all the official codecs; pretty, compact, ber, per and erlang.

Functions

start()

Equivalent to start/1.

start(MessagePackage)

-spec start([MessagePackage]) -> ok when MessagePackage :: atom();
           (MessagePackage) -> ok when MessagePackage :: atom();
           (Factor) -> ok when Factor :: pos_integer().

This function runs the measurement on all the official codecs; pretty, compact, ber, per and erlang.

This function is intended to be called from the meas script, which uses the '-s' arguments to run the function:

erl -s megaco_codec_meas start time_test

megaco_codec_mstone1

This module implements a simple megaco codec-based performance tool.

This module implements the mstone1 tool, a simple megaco codec-based performance tool.

The results, the mstone value(s), are written to stdout.

Note that this module is not included in the runtime part of the application.

Summary

Functions

start()

Equivalent to start/2.

start([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor)

start(MessagePackage, Factor)

This function starts the mstone1 performance test with all codec configs. Factor (defaults to 1) processes are started for every supported codec config.

start_flex()

Equivalent to start_flex/2.

start_flex([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor)

start_flex(MessagePackage, Factor)

This function starts the mstone1 performance test with only the flex codec configs (i.e. pretty and compact with flex). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

start_no_drv()

Equivalent to start_no_drv/2.

start_no_drv([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor)

start_no_drv(MessagePackage, Factor)

This function starts the mstone1 performance test with codec configs not using any drivers (i.e. pretty and compact without flex, ber and per without driver and erlang without compressed). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

start_only_drv()

Equivalent to start_only_drv/2.

start_only_drv/1

start_no_drv([MessagePackage, RunTime, Factor])

start_only_drv(MessagePackage, Factor)

This function starts the mstone1 performance test with only the driver using codec configs (i.e. pretty and compact with flex, and ber and per with driver and erlang with compressed). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

Functions

start()

Equivalent to start/2.

start([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor):

erl -s megaco_codec_mstone1 start time_test 1 1

start(MessagePackage, Factor)

-spec start(RunTime, Factor) -> ok when RunTime :: pos_integer(), Factor :: default | pos_integer();
           (MessagePackage, Factor) -> ok when MessagePackage :: atom(), Factor :: pos_integer().

This function starts the mstone1 performance test with all codec configs. Factor (defaults to 1) processes are started for every supported codec config.

Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

start_flex()

Equivalent to start_flex/2.

start_flex([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor):

erl -s megaco_codec_mstone1 start_flex time_test 1 1

start_flex(MessagePackage, Factor)

-spec start_flex(MessagePackage, Factor) -> ok when MessagePackage :: atom(), Factor :: pos_integer().

This function starts the mstone1 performance test with only the flex codec configs (i.e. pretty and compact with flex). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

start_no_drv()

Equivalent to start_no_drv/2.

start_no_drv([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor):

erl -s megaco_codec_mstone1 start_no_drv time_test 1 1

start_no_drv(MessagePackage, Factor)

-spec start_no_drv(MessagePackage, Factor) -> ok when MessagePackage :: atom(), Factor :: pos_integer().

This function starts the mstone1 performance test with codec configs not using any drivers (i.e. pretty and compact without flex, ber and per without driver and erlang without compressed). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

start_only_drv()

Equivalent to start_only_drv/2.

start_only_drv/1

start_no_drv([MessagePackage, RunTime, Factor])

This function is intended to be called from the mstone1 script, which uses the '-s' arguments to run the function (argument order; message package, run time (in minutes in the example) and factor):

erl -s megaco_codec_mstone1 start_no_drv time_test 1 1

start_only_drv(MessagePackage, Factor)

-spec start_only_drv(MessagePackage, Factor) -> ok
                        when MessagePackage :: atom(), Factor :: pos_integer().

This function starts the mstone1 performance test with only the driver using codec configs (i.e. pretty and compact with flex, and ber and per with driver and erlang with compressed). The same number of processes are started as when running the standard test (using the start/0,1 function). Each process encodes and decodes their messages. The number of messages processed in total (for all processes) is the mstone value.

megaco_codec_mstone2

This module implements a simple megaco codec-based performance tool.

This module implements the mstone2 tool, a simple megaco codec-based performance tool.

The results, the mstone value(s), are written to stdout.

Note that this module is not included in the runtime part of the application.

Summary

Functions

start()

Equivalent to start/1.

start/1

start(RunTime | MessagePackage)

Functions

start()

Equivalent to start/1.

start/1

-spec start(RunTime) -> ok when RunTime :: pos_integer();
           (MessagePackage) -> ok when MessagePackage :: atom().

start(RunTime | MessagePackage)

This function starts the mstone2 performance test with all codec configs. Processes are created dynamically. Each process make one run through their messages (decoding and encoding messages) and then exits. When one process exits, a new is created with the same codec config and set of messages.

The number of messages processed in total (for all processes) is the mstone value.

megaco_codec_transform

Megaco message transformation utility.

This module implements a simple megaco message transformation utility.

Note that this module is not included in the runtime part of the application.

Summary

Functions

export_messages()

Equivalent to export_messages/1.

export_messages(MessagePackage)

Export the messages in the MessagePackage (default is time_test).

Functions

export_messages()

Equivalent to export_messages/1.

export_messages(MessagePackage)

-spec export_messages(MessagePackage) -> ok | {error, Reason}
                         when MessagePackage :: atom(), Reason :: term().

Export the messages in the MessagePackage (default is time_test).

The output produced by this function is a directory structure with the following structure:

<message package>/pretty/<message-files>
                  compact/<message-files>
                  per/<message-files>
                  ber/<message-files>
                  erlang/<message-files>

megaco_digit_map

Digit Map utility module.

This is a Digit Map utility module (types).

Version note

This module has existed in the megaco app for long time, but as of 27.0, its also documented.

Summary

Types

cancel()

$z | $Z | cancel

event()

kind()

letter()

$0..$9 | $a..$k | $A..$K

one_second()

$s | $S

pause()

ten_seconds()

$l | $L

value()

Types

cancel()

(since OTP 27.0)

-type cancel() :: $z | $Z | cancel.

$z | $Z | cancel

event()

(since OTP 27.0)

-type event() :: letter() | pause() | cancel().

kind()

(since OTP 27.0)

-type kind() :: full | unambiguous.

letter()

(since OTP 27.0)

-type letter() :: $0..$9 | $a..$k | $A..$K.

$0..$9 | $a..$k | $A..$K

one_second()

(since OTP 27.0)

-type one_second() :: $s | $S.

$s | $S

pause()

(since OTP 27.0)

-type pause() :: one_second() | ten_seconds().

ten_seconds()

(since OTP 27.0)

-type ten_seconds() :: $l | $L.

$l | $L

value()

(since OTP 27.0)

-type value() ::
          #'DigitMapValue'{startTimer :: term(),
                           shortTimer :: term(),
                           longTimer :: term(),
                           digitMapBody :: term(),
                           durationTimer :: term()}.

megaco_edist_compress behaviour

Megaco erlang dist compress behaviour.

The following functions should be exported from a megaco_edist_compress callback module:

Summary

Callbacks

decode(T, Version)

Decompress a megaco component.

encode(R, Version)

Compress a megaco component. The erlang dist encoder makes no assumption on the how or even if the component is compressed.

Callbacks

decode(T, Version)

-callback decode(T, Version) -> R
                    when
                        T :: term(),
                        Version :: megaco_encoder:protocol_version() | dynamic,
                        R ::
                            megaco_encoder:megaco_message() |
                            megaco_encoder:transaction() |
                            megaco_encoder:action_reply() |
                            megaco_encoder:action_request() |
                            megaco_encoder:command_request().

Decompress a megaco component.

encode(R, Version)

-callback encode(R, Version) -> T
                    when
                        R ::
                            megaco_encoder:megaco_message() |
                            megaco_encoder:transaction() |
                            megaco_encoder:action_reply() |
                            megaco_encoder:action_request() |
                            megaco_encoder:command_request(),
                        Version :: megaco_encoder:protocol_version(),
                        T :: term().

Compress a megaco component. The erlang dist encoder makes no assumption on the how or even if the component is compressed.

megaco_encoder behaviour

Megaco encoder behaviour.

The following functions should be exported from a megaco_encoder callback module:

DATA TYPES

Note

Note that the actual definition of (some of) these records depend on the megaco protocol version used. For instance, the 'TransactionReply' record has two more fields in version 3, so a simple erlang type definition cannot be made here.

protocol_version() = integer()
segment_no()       = integer()
megaco_message() = #'MegacoMessage{}'
transaction() = {transactionRequest,     transaction_request()}      |
                {transactionPending,     transaction_reply()}        |
                {transactionReply,       transaction_pending()}      |
                {transactionResponseAck, transaction_response_ack()} |
                {segmentReply,           segment_reply()}
transaction_request() = #'TransactionRequest'{}
transaction_pending() = #'TransactionPending'{}
transaction_reply() = #'TransactionReply'{}
transaction_response_ack() = [transaction_ack()]
transaction_ack() = #'TransactionAck'{}
segment_reply() = #'SegmentReply'{}
action_request() = #'ActionRequest'{}
action_reply() = #'ActionReply'{}
command_request() = #'CommandRequest'{}
error_desc()   = #'ErrorDescriptor'{}

Summary

Types

action_reply()

action_request()

alpha()

Alpha Numeric characters: A..Z | a..z

command_request()

deviceName()

digit()

Decimal digits: 0..9

domainName()

error_desc()

ip4Address()

ip6Address()

megaco_message()

mtpAddress()

There is no way to properly express this type in the Erlang type system, so this is the best we can do.

octet()

octet_string()

pathName()

There is no way to properly express this type in the Erlang type system, so this is the best we can do. The minimum length is 1 and the maximum length is 64.

protocol_version()

segment_no()

segment_reply()

transaction()

transaction_ack()

transaction_pending()

transaction_reply()

The problem with TransactionReply is that its definition depend on which version of the protocol we are using. As of version 3, it has two more fields.

transaction_request()

transaction_response_ack()

Callbacks

decode_message(EncodingConfig, Version, Bin)

Decode a megaco message.

decode_mini_message(EncodingConfig, Version, Bin)

Perform a minimal decode of a megaco message.

encode_action_reply(EncodingConfig, Version, AR)

Encode a megaco action reply. If this, for whatever reason, is not supported, the function should return the error reason not_implemented.

encode_action_requests(EncodingConfig, Version, ARs)

Encode megaco action requests. This function is called when the user calls the function encode_actions/3. If that function is never used or if the codec cannot support this (the encoding of individual actions), then return with error reason not_implemented.

encode_message(EncodingConfig, Version, Message)

Encode a megaco message.

encode_transaction(EncodingConfig, Version, Transaction)

Encode a megaco transaction. If this, for whatever reason, is not supported, the function should return the error reason not_implemented.

Types

action_reply()

-type action_reply() :: {'ActionReply', _, _, _, _}.

action_request()

-type action_request() :: {'ActionRequest', _, _, _, _}.

alpha()

-type alpha() :: 65..90 | 97..122.

Alpha Numeric characters: A..Z | a..z

command_request()

-type command_request() :: {'CommandRequest', _, _, _}.

deviceName()

-type deviceName() :: pathName().

digit()

-type digit() :: 48..57.

Decimal digits: 0..9

domainName()

-type domainName() :: #'DomainName'{name :: term(), portNumber :: term()}.

error_desc()

-type error_desc() :: #'ErrorDescriptor'{errorCode :: term(), errorText :: term()}.

ip4Address()

-type ip4Address() :: #'IP4Address'{address :: term(), portNumber :: term()}.

ip6Address()

-type ip6Address() :: #'IP6Address'{address :: term(), portNumber :: term()}.

megaco_message()

-type megaco_message() :: #'MegacoMessage'{authHeader :: term(), mess :: term()}.

mtpAddress()

-type mtpAddress() :: octet_string().

There is no way to properly express this type in the Erlang type system, so this is the best we can do.

A proper definition would be: -type mtpAddress() :: octet_string(2..4).

octet()

-type octet() :: 0..255.

octet_string()

-type octet_string() :: [octet()].

pathName()

-type pathName() :: [$* | alpha() | digit() | $_ | $/ | $$ | $@ | $- | $.].

There is no way to properly express this type in the Erlang type system, so this is the best we can do. The minimum length is 1 and the maximum length is 64.

Here is the ABNF (copied from the megaco standard) to fill in the blanks:

# Total length of pathNAME must not exceed 64 chars.

pathNAME = ["*"] NAME *("/" / "*"/ ALPHA / DIGIT /"_" / "$" ) ["@" pathDomainName ]

# ABNF allows two or more consecutive "." although it is meaningless in a path domain name.

pathDomainName = (ALPHA / DIGIT / "*" ) *63(ALPHA / DIGIT / "-" / "*" / ".")

NAME = ALPHA *63(ALPHA / DIGIT / "_" )

protocol_version()

-type protocol_version() :: pos_integer().

segment_no()

-type segment_no() :: 0..65535.

segment_reply()

-type segment_reply() ::
          #'SegmentReply'{transactionId :: term(),
                          segmentNumber :: term(),
                          segmentationComplete :: term()}.

transaction()

-type transaction() ::
          {transactionRequest, transaction_request()} |
          {transactionPending, transaction_reply()} |
          {transactionReply, transaction_pending()} |
          {transactionResponseAck, transaction_response_ack()} |
          {segmentReply, segment_reply()}.

transaction_ack()

-type transaction_ack() :: #'TransactionAck'{firstAck :: term(), lastAck :: term()}.

transaction_pending()

-type transaction_pending() :: #'TransactionPending'{transactionId :: term()}.

transaction_reply()

-type transaction_reply() :: {'TransactionReply', _, _} | {'TransactionReply', _, _, _, _}.

The problem with TransactionReply is that its definition depend on which version of the protocol we are using. As of version 3, it has two more fields.

transaction_request()

-type transaction_request() :: #'TransactionRequest'{transactionId :: term(), actions :: term()}.

transaction_response_ack()

-type transaction_response_ack() :: [transaction_ack()].

Callbacks

decode_message(EncodingConfig, Version, Bin)

-callback decode_message(EncodingConfig, Version, Bin) -> {ok, Message} | Error
                            when
                                EncodingConfig :: list(),
                                Version :: protocol_version() | dynamic,
                                Bin :: binary(),
                                Message :: megaco_message(),
                                Error :: term().

Decode a megaco message.

Note that if the Version argument is dynamic, the decoder should try to figure out the actual version from the message itself and then use the proper decoder, e.g. version 1.
If on the other hand the Version argument is an integer, it means that this is the expected version of the message and the decoder for that version should be used.

decode_mini_message(EncodingConfig, Version, Bin)

-callback decode_mini_message(EncodingConfig, Version, Bin) -> {ok, Message} | Error
                                 when
                                     EncodingConfig :: list(),
                                     Version :: protocol_version() | dynamic,
                                     Bin :: binary(),
                                     Message :: megaco_message(),
                                     Error :: term().

Perform a minimal decode of a megaco message.

The purpose of this function is to do a minimal decode of Megaco message. A successfull result is a 'MegacoMessage' in which only version and mid has been initiated. This function is used by the megaco_messenger module when the decode_message/3 function fails to figure out the mid (the actual sender) of the message.

Note again that a successfull decode only returns a partially initiated message.

encode_action_reply(EncodingConfig, Version, AR)

(optional)

-callback encode_action_reply(EncodingConfig, Version, AR) -> {ok, Bin} | {error, Reason}
                                 when
                                     EncodingConfig :: list(),
                                     Version :: protocol_version(),
                                     AR :: action_reply(),
                                     Bin :: binary(),
                                     Reason :: not_implemented | term().

Encode a megaco action reply. If this, for whatever reason, is not supported, the function should return the error reason not_implemented.

This function is used when segmentation has been configured. So, for this to work, this function must be fully supported!

encode_action_requests(EncodingConfig, Version, ARs)

-callback encode_action_requests(EncodingConfig, Version, ARs) -> {ok, Bin} | {error, Reason}
                                    when
                                        EncodingConfig :: list(),
                                        Version :: protocol_version(),
                                        ARs :: [action_request()],
                                        Bin :: binary(),
                                        Reason :: not_implemented | term().

Encode megaco action requests. This function is called when the user calls the function encode_actions/3. If that function is never used or if the codec cannot support this (the encoding of individual actions), then return with error reason not_implemented.

encode_message(EncodingConfig, Version, Message)

-callback encode_message(EncodingConfig, Version, Message) -> {ok, Bin} | Error
                            when
                                EncodingConfig :: list(),
                                Version :: protocol_version(),
                                Message :: megaco_message(),
                                Bin :: binary(),
                                Error :: term().

Encode a megaco message.

encode_transaction(EncodingConfig, Version, Transaction)

-callback encode_transaction(EncodingConfig, Version, Transaction) -> {ok, Bin} | {error, Reason}
                                when
                                    EncodingConfig :: list(),
                                    Version :: protocol_version(),
                                    Transaction :: transaction(),
                                    Bin :: binary(),
                                    Reason :: not_implemented | term().

Encode a megaco transaction. If this, for whatever reason, is not supported, the function should return the error reason not_implemented.

This functionality is used both when the transaction sender is used and for segmentation. So, for either of those to work, this function must be fully supported!

megaco_flex_scanner

Interface module to the flex scanner linked in driver.

This module contains the public interface to the flex scanner linked in driver. The flex scanner performs the scanning phase of text message decoding.

The flex scanner is written using a tool called flex. In order to be able to compile the flex scanner driver, this tool has to be available.

By default the flex scanner reports line-number of an error. But it can be built without line-number reporting. Instead token number is used. This will speed up the scanning some 5-10%. Use --disable-megaco-flex-scanner-lineno when configuring the application.

The scanner will, by default, be built as a reentrant scanner if the flex utility supports this (it depends on the version of flex). It is possible to explicitly disable this even when flex support this. Use --disable-megaco-reentrant-flex-scanner when configuring the application.

Summary

Types

megaco_ports()

Return value of a successful (flex) scanner start.

Functions

is_reentrant_enabled()

Is the flex scanner reentrant or not.

is_scanner_port(Port, PortOrPorts)

Checks if a port is a flex scanner port or not (useful when if a port exits).

scan(Binary, PortOrPorts)

Scans a megaco message and generates a token list to be passed on the parser.

start()

This function is used to start the flex scanner. It locates the library and loads the linked in driver.

stop(PortOrPorts)

This function is used to stop the flex scanner. It also unloads the driver.

Types

megaco_ports()

-type megaco_ports() :: port() | tuple().

Return value of a successful (flex) scanner start.

Functions

is_reentrant_enabled()

-spec is_reentrant_enabled() -> boolean().

Is the flex scanner reentrant or not.

is_scanner_port(Port, PortOrPorts)

-spec is_scanner_port(Port, PortOrPorts) -> boolean() when Port :: port(), PortOrPorts :: megaco_ports().

Checks if a port is a flex scanner port or not (useful when if a port exits).

scan(Binary, PortOrPorts)

-spec scan(Binary, PortOrPorts) -> {ok, Tokens, Version, LatestLine} | {error, Reason, LatestLine}
              when
                  Binary :: binary(),
                  PortOrPorts :: megaco_ports(),
                  Tokens :: list(),
                  Version :: megaco_encoder:protocol_version(),
                  LatestLine :: non_neg_integer(),
                  Reason :: term().

Scans a megaco message and generates a token list to be passed on the parser.

start()

-spec start() -> {ok, PortOrPorts} | {error, Reason}
               when PortOrPorts :: megaco_ports(), Reason :: term().

This function is used to start the flex scanner. It locates the library and loads the linked in driver.

On a single core system or if it's a non-reentrant scanner, a single port is created. On a multi-core system with a reentrant scanner, several ports will be created (one for each scheduler).

Note that the process that calls this function must be permanent. If it dies, the port(s) will exit and the driver unload.

stop(PortOrPorts)

-spec stop(PortOrPorts) -> stopped when PortOrPorts :: megaco_ports().

This function is used to stop the flex scanner. It also unloads the driver.

megaco_sdp

SDP utility module.

This module contains various things related to SDP.

Version note

This module has existed in the megaco app for long time, but as of 27.0 its also documented.

Summary

Types

property_group()

property_groups()

property_parm()

sdp()

sdp_a()

Session attribute.

sdp_a_fmtp()

sdp_a_ptime()

sdp_a_quality()

sdp_a_rtpmap()

sdp_b()

Bandwidth information.

sdp_c()

Connection information.

sdp_e()

Email address.

sdp_i()

Session information.

sdp_k()

Encryption key.

sdp_m()

Media name and transport address.

sdp_o()

Owner/creator and session identifier.

sdp_p()

Phone number.

sdp_property_group()

sdp_property_groups()

sdp_property_parm()

sdp_r()

Repeat times.

sdp_s()

Session name.

sdp_t()

sdp_u()

URI of description.

sdp_v()

Protocol version.

sdp_z()

Time zone adjustment.

Types

property_group()

(since OTP 27.0)

-type property_group() :: [property_parm()].

property_groups()

(since OTP 27.0)

-type property_groups() :: [property_group()].

property_parm()

(since OTP 27.0)

-type property_parm() :: #'PropertyParm'{name :: term(), value :: term(), extraInfo :: term()}.

sdp()

(since OTP 27.0)

-type sdp() ::
          sdp_o() |
          sdp_s() |
          sdp_i() |
          sdp_u() |
          sdp_e() |
          sdp_p() |
          sdp_c() |
          sdp_b() |
          sdp_k() |
          sdp_a() |
          sdp_a_rtpmap() |
          sdp_a_ptime() |
          sdp_z() |
          sdp_t() |
          sdp_r() |
          sdp_m().

sdp_a()

(since OTP 27.0)

-type sdp_a() :: #megaco_sdp_a{attribute :: term(), value :: term()}.

Session attribute.

sdp_a_fmtp()

(since OTP 27.0)

-type sdp_a_fmtp() :: #megaco_sdp_a_fmtp{format :: term(), param :: term()}.

sdp_a_ptime()

(since OTP 27.0)

-type sdp_a_ptime() :: #megaco_sdp_a_ptime{packet_time :: term()}.

sdp_a_quality()

(since OTP 27.0)

-type sdp_a_quality() :: #megaco_sdp_a_quality{quality :: term()}.

sdp_a_rtpmap()

(since OTP 27.0)

-type sdp_a_rtpmap() ::
          #megaco_sdp_a_rtpmap{payload_type :: term(),
                               encoding_name :: term(),
                               clock_rate :: term(),
                               encoding_parms :: term()}.

sdp_b()

(since OTP 27.0)

-type sdp_b() :: #megaco_sdp_b{bwtype :: term(), bandwidth :: term()}.

Bandwidth information.

sdp_c()

(since OTP 27.0)

-type sdp_c() ::
          #megaco_sdp_c{network_type :: term(), address_type :: term(), connection_addr :: term()}.

Connection information.

sdp_e()

(since OTP 27.0)

-type sdp_e() :: #megaco_sdp_e{email :: term()}.

Email address.

sdp_i()

(since OTP 27.0)

-type sdp_i() :: #megaco_sdp_i{session_descriptor :: term()}.

Session information.

sdp_k()

(since OTP 27.0)

-type sdp_k() :: #megaco_sdp_k{method :: term(), encryption_key :: term()}.

Encryption key.

sdp_m()

(since OTP 27.0)

-type sdp_m() ::
          #megaco_sdp_m{media :: term(),
                        port :: term(),
                        num_ports :: term(),
                        transport :: term(),
                        fmt_list :: term()}.

Media name and transport address.

sdp_o()

(since OTP 27.0)

-type sdp_o() ::
          #megaco_sdp_o{user_name :: term(),
                        session_id :: term(),
                        version :: term(),
                        network_type :: term(),
                        address_type :: term(),
                        address :: term()}.

Owner/creator and session identifier.

sdp_p()

(since OTP 27.0)

-type sdp_p() :: #megaco_sdp_p{phone_number :: term()}.

Phone number.

sdp_property_group()

(since OTP 27.0)

-type sdp_property_group() :: [sdp_property_parm()].

sdp_property_groups()

(since OTP 27.0)

-type sdp_property_groups() :: [sdp_property_group()].

sdp_property_parm()

(since OTP 27.0)

-type sdp_property_parm() :: sdp() | property_parm().

sdp_r()

(since OTP 27.0)

-type sdp_r() ::
          #megaco_sdp_r{repeat_interval :: term(), active_duration :: term(), list_of_offsets :: term()}.

Repeat times.

sdp_s()

(since OTP 27.0)

-type sdp_s() :: #megaco_sdp_s{name :: term()}.

Session name.

sdp_t()

(since OTP 27.0)

-type sdp_t() :: #megaco_sdp_t{start :: term(), stop :: term()}.

sdp_u()

(since OTP 27.0)

-type sdp_u() :: #megaco_sdp_u{uri :: term()}.

URI of description.

sdp_v()

(since OTP 27.0)

-type sdp_v() :: #megaco_sdp_v{version :: term()}.

Protocol version.

sdp_z()

(since OTP 27.0)

-type sdp_z() :: #megaco_sdp_z{list_of_adjustments :: term()}.

Time zone adjustment.

megaco_tcp

Interface module to TPKT transport protocol for Megaco/H.248.

This module contains the public interface to the TPKT (TCP/IP) version transport protocol for Megaco/H.248.

Summary

Types

counter()

Defines the different counters handled by this transport.

handle()

An opaque data type representing a TPKT connection.

Functions

block(Handle)

Stop receiving incoming messages on the socket.

close(Handle)

This function is used for closing an active TPKT connection.

connect(TransportRef, Opts)

This function is used to open a TPKT connection.

get_stats()

Get all counter values for all known connections.

get_stats(Handle)

Get all counter values for a given (connection) handle.

get_stats(Handle, Counter)

Get the value of a specific counter.

listen(TransportRef, Options)

This function is used for starting new TPKT listening socket for TCP/IP. The option list contains the socket definitions.

reset_stats()

Reset all counters for all connections.

reset_stats(Handle)

Reset all counters for the given connection.

send_message(Handle, Msg)

Sends a message on a TPKT connection.

socket(Handle)

This function is used to convert a socket handle() to a inet socket().

start_transport()

This function is used for starting the TCP/IP transport service. Use exit(TransportRef, Reason) to stop the transport service.

unblock(Handle)

Starting to receive incoming messages from the socket again.

upgrade_receive_handle(ControlPid, NewRecvHandle)

Upgrade the receive handle of the control process (e.g. after having changed protocol version).

Types

counter()

-type counter() ::
          medGwyGatewayNumInMessages | medGwyGatewayNumInOctets | medGwyGatewayNumOutMessages |
          medGwyGatewayNumOutOctets | medGwyGatewayNumErrors.

Defines the different counters handled by this transport.

handle()

-opaque handle()

An opaque data type representing a TPKT connection.

Functions

block(Handle)

-spec block(Handle) -> ok when Handle :: handle().

Stop receiving incoming messages on the socket.

close(Handle)

-spec close(Handle) -> ok when Handle :: handle().

This function is used for closing an active TPKT connection.

connect(TransportRef, Opts)

-spec connect(TransportRef, Opts) -> {ok, Handle, ControlPid} | {error, Reason}
                 when
                     TransportRef :: pid() | RegName,
                     RegName :: atom(),
                     Opts :: [Option],
                     Option ::
                         {inet_backend, default | inet | socket} |
                         {host, Host} |
                         {port, PortNum} |
                         {options, list()} |
                         {receive_handle, term()} |
                         {module, atom()},
                     Host :: inet:socket_address() | inet:hostname(),
                     PortNum :: inet:port_number(),
                     Handle :: handle(),
                     ControlPid :: pid(),
                     Reason :: term().

This function is used to open a TPKT connection.

module - This option makes it possible for the user to provide their own callback module. The receive_message/4 or process_received_message/4 functions of this module is called when a new message is received. Which one is called depends on the size of the message;

small - receive_message

large - process_received_message

Default value is megaco.

inet_backend - Choose the inet-backend.

This option make it possible to use a different inet-backend ('default', 'inet' or 'socket').

Default is default (system default).

get_stats()

-spec get_stats() -> {ok, TotalStats} | {error, Reason}
                   when
                       TotalStats :: [{Handle, [{Counter, integer()}]}],
                       Handle :: handle(),
                       Counter :: counter(),
                       Reason :: term().

Get all counter values for all known connections.

get_stats(Handle)

-spec get_stats(Handle) -> {ok, Stats} | {error, Reason}
                   when
                       Handle :: handle(),
                       Stats :: [{Counter, integer()}],
                       Counter :: counter(),
                       Reason :: term().

Get all counter values for a given (connection) handle.

get_stats(Handle, Counter)

-spec get_stats(Handle, Counter) -> {ok, integer()} | {error, Reason}
                   when Handle :: handle(), Counter :: counter(), Reason :: term().

Get the value of a specific counter.

listen(TransportRef, Options)

-spec listen(TransportRef, Options) -> ok
                when
                    TransportRef :: pid() | RegName,
                    RegName :: atom(),
                    Options :: [Option],
                    Option ::
                        {inet_backend, default | inet | socket} |
                        {port, inet:port_number()} |
                        {options, list()} |
                        {receive_handle, term()}.

This function is used for starting new TPKT listening socket for TCP/IP. The option list contains the socket definitions.

inet_backend - Choose the inet-backend.

This option make it possible to use a different inet-backend ('default', 'inet' or 'socket').

Default is default (system default).

reset_stats()

-spec reset_stats() -> megaco:void().

Reset all counters for all connections.

reset_stats(Handle)

-spec reset_stats(Handle) -> megaco:void() when Handle :: handle().

Reset all counters for the given connection.

send_message(Handle, Msg)

-spec send_message(Handle, Msg) -> ok when Handle :: handle(), Msg :: binary() | iolist().

Sends a message on a TPKT connection.

socket(Handle)

-spec socket(Handle) -> Socket when Handle :: handle(), Socket :: inet:socket().

This function is used to convert a socket handle() to a inet socket().

start_transport()

-spec start_transport() -> {ok, TransportRef} when TransportRef :: pid().

This function is used for starting the TCP/IP transport service. Use exit(TransportRef, Reason) to stop the transport service.

unblock(Handle)

-spec unblock(Handle) -> ok when Handle :: handle().

Starting to receive incoming messages from the socket again.

upgrade_receive_handle(ControlPid, NewRecvHandle)

-spec upgrade_receive_handle(ControlPid, NewRecvHandle) -> ok
                                when ControlPid :: pid(), NewRecvHandle :: term().

Upgrade the receive handle of the control process (e.g. after having changed protocol version).

megaco_transport behaviour

Megaco transport behaviour.

The following functions should be exported from a megaco_transport callback module:

send_message/2 [mandatory]

send_message/3 [optional]

resend_message/2 [optional]

Summary

Callbacks

resend_message(Handle, Msg)

Re-send a megaco message.

send_message(Handle, Msg)

Equivalent to send_message/3.

send_message(Handle, Msg, Resend)

Send a megaco message.

Callbacks

resend_message(Handle, Msg)

(optional)

-callback resend_message(Handle, Msg) -> ok | {cancel, Reason :: term()} | Error
                            when Handle :: term(), Msg :: iodata(), Error :: term().

Re-send a megaco message.

Note that this function will only be called if the user has set the resend_indication config option to trueand it is in fact a message resend. If not both of these condition's are meet, send_message will be called.

If the function returns {cancel, Reason}, this means the transport module decided not to send the message. This is not an error. No error messages will be issued and no error counters incremented. What actions this will result in depends on what kind of message was sent.

In the case of requests, megaco will cancel the message in much the same way as if megaco:cancel had been called (after a successfull send). The information will be propagated back to the user differently depending on how the request(s) where issued: For requests issued using megaco:call, the info will be delivered in the return value. For requests issued using megaco:cast the info will be delivered via a call to the callback function handle_trans_reply.

In the case of reply, megaco will cancel the reply and information of this will be returned to the user via a call to the callback function handle_trans_ack.

send_message(Handle, Msg)

-callback send_message(Handle, Msg) -> ok | {cancel, Reason :: term()} | Error
                          when Handle :: term(), Msg :: iodata(), Error :: term().

Equivalent to send_message/3.

send_message(Handle, Msg, Resend)

(optional)

-callback send_message(Handle, Msg, Resend) -> ok | {cancel, Reason :: term()} | Error
                          when Handle :: term(), Msg :: iodata(), Resend :: boolean(), Error :: term().

Send a megaco message.

If the function returns {cancel, Reason}, this means the transport module decided not to send the message. This is not an error. No error messages will be issued and no error counters incremented. What actions this will result in depends on what kind of message was sent.

In the case of requests, megaco will cancel the message in much the same way as if megaco:cancel had been called (after a successfull send). The information will be propagated back to the user differently depending on how the request(s) where issued: For requests issued using megaco:call/3, the info will be delivered in the return value. For requests issued using megaco:cast the info will be delivered via a call to the callback function handle_trans_reply.

In the case of reply, megaco will cancel the reply and information of this will be returned to the user via a call to the callback function handle_trans_ack.

The function send_message/3 will only be called if the resend_indication config option has been set to the value flag. The third argument, Resend then indicates if the message send is a resend or not.

megaco_udp

Interface module to UDP transport protocol for Megaco/H.248.

This module contains the public interface to the UDP/IP version transport protocol for Megaco/H.248.

Summary

Types

counter()

Defines the different counters handled by this transport.

handle()

An opaque data type representing an UDP socket.

send_handle()

An opaque data type representing an UDP socket, used when sending.

Functions

block(Handle)

Stop receiving incoming messages on the socket.

close(Handle)

This function is used for closing an active UDP socket.

create_send_handle(Handle, Host, Port)

Creates a send handle from a transport handle. The send handle is intended to be used by megaco_udp:send_message/2.

get_stats()

Get all counter values for all known connections.

get_stats(SH)

Get all counter values for a given handle.

get_stats(SH, Counter)

Get the value of a specific counter.

open(TransportRef, Opts)

This function is used to open an UDP/IP socket.

reset_stats()

Reset all counters for all UDP handles.

reset_stats(SH)

Reset all counters for the given UDP handle.

send_message(SH, Msg)

Sends a message on a socket. The send handle is obtained by megacoudp:create_send_handle/3. Increments the NumOutMessages and NumOutOctets counters if message successfully sent. In case of a failure to send, the NumErrors counter is _not incremented. This is done elsewhere in the megaco app.

socket(Handle)

This function is used to convert a socket handle() to a inet socket().

start_transport()

This function is used for starting the UDP/IP transport service. Use exit(TransportRef, Reason) to stop the transport service.

unblock(Handle)

Starting to receive incoming messages from the socket again.

upgrade_receive_handle(ControlPid, NewRecvHandle)

Update the receive handle of the control process (e.g. after having changed protocol version).

Types

counter()

-type counter() ::
          medGwyGatewayNumInMessages | medGwyGatewayNumInOctets | medGwyGatewayNumOutMessages |
          medGwyGatewayNumOutOctets | medGwyGatewayNumErrors.

Defines the different counters handled by this transport.

handle()

-opaque handle()

An opaque data type representing an UDP socket.

send_handle()

-opaque send_handle()

An opaque data type representing an UDP socket, used when sending.

Functions

block(Handle)

-spec block(Handle) -> ok when Handle :: handle() | send_handle().

Stop receiving incoming messages on the socket.

close(Handle)

-spec close(Handle) -> ok when Handle :: handle() | send_handle().

This function is used for closing an active UDP socket.

create_send_handle(Handle, Host, Port)

-spec create_send_handle(Handle, Host, Port) -> send_handle()
                            when
                                Handle :: handle(),
                                Host :: inet:ip4_address() | inet:hostname(),
                                Port :: inet:port_number().

Creates a send handle from a transport handle. The send handle is intended to be used by megaco_udp:send_message/2.

get_stats()

-spec get_stats() -> {ok, TotalStats} | {error, Reason}
                   when
                       TotalStats :: [{SH, [{Counter, integer()}]}],
                       SH :: send_handle(),
                       Counter :: counter(),
                       Reason :: term().

Get all counter values for all known connections.

get_stats(SH)

-spec get_stats(SH) -> {ok, Stats} | {error, Reason}
                   when
                       SH :: send_handle(),
                       Stats :: [{Counter, integer()}],
                       Counter :: counter(),
                       Reason :: term().

Get all counter values for a given handle.

get_stats(SH, Counter)

-spec get_stats(SH, Counter) -> {ok, integer()} | {error, Reason}
                   when SH :: send_handle(), Counter :: counter(), Reason :: term().

Get the value of a specific counter.

open(TransportRef, Opts)

-spec open(TransportRef, Opts) -> {ok, Handle, ControlPid} | {error, Reason}
              when
                  TransportRef :: pid(),
                  Opts ::
                      {inet_backend, default | inet | socket} |
                      {port, PortNum} |
                      {options, list()} |
                      {receive_handle, term()} |
                      {module, atom()},
                  PortNum :: inet:port_number(),
                  Handle :: handle(),
                  ControlPid :: pid(),
                  Reason :: term().

This function is used to open an UDP/IP socket.

module - The option makes it possible for the user to provide their own callback module. The functions receive_message/4 or process_received_message/4 of this module is called when a new message is received. Which one depends on the size of the message:

small - receive_message

large - process_received_message

Default value is megaco.

inet_backend - Choose the inet-backend.

This option make it possible to use a different inet-backend ('default', 'inet' or 'socket').

Default is default (system default).

reset_stats()

-spec reset_stats() -> megaco:void().

Reset all counters for all UDP handles.

reset_stats(SH)

-spec reset_stats(SH) -> megaco:void() when SH :: send_handle().

Reset all counters for the given UDP handle.

send_message(SH, Msg)

-spec send_message(SH, Msg) -> ok when SH :: send_handle(), Msg :: binary() | iolist().

Sends a message on a socket. The send handle is obtained by megacoudp:create_send_handle/3. Increments the NumOutMessages and NumOutOctets counters if message successfully sent. In case of a failure to send, the NumErrors counter is _not incremented. This is done elsewhere in the megaco app.

socket(Handle)

-spec socket(Handle) -> Socket when Handle :: handle() | send_handle(), Socket :: inet:socket().

This function is used to convert a socket handle() to a inet socket().

start_transport()

-spec start_transport() -> {ok, TransportRef} when TransportRef :: pid().

This function is used for starting the UDP/IP transport service. Use exit(TransportRef, Reason) to stop the transport service.

unblock(Handle)

-spec unblock(Handle) -> ok when Handle :: handle() | send_handle().

Starting to receive incoming messages from the socket again.

upgrade_receive_handle(ControlPid, NewRecvHandle)

-spec upgrade_receive_handle(ControlPid, NewRecvHandle) -> ok
                                when ControlPid :: pid(), NewRecvHandle :: term().

Update the receive handle of the control process (e.g. after having changed protocol version).

megaco_user behaviour

Callback module for users of the Megaco application

This module defines the callback behaviour of Megaco users. A megaco_user compliant callback module must export the following functions:

handle_connect/2,3

handle_disconnect/3

handle_syntax_error/3,4

handle_message_error/3,4

handle_trans_request/3,4

handle_trans_long_request/3,4

handle_trans_reply/4,5

handle_trans_ack/4,5

handle_unexpected_trans/3,4

handle_trans_request_abort/4,5

handle_segment_reply/5,6

The semantics of them and their exact signatures are explained below.

The user_args configuration parameter which may be used to extend the argument list of the callback functions. For example, the handle_connect function takes by default two arguments:

handle_connect(Handle, Version)

but if the user_args parameter is set to a longer list, such as [SomePid,SomeTableRef], the callback function is expected to have these (in this case two) extra arguments last in the argument list:

handle_connect(Handle, Version, SomePid, SomeTableRef)

Note

Must of the functions below has an optional Extra argument (e.g. handle_unexpected_trans/4). The functions which takes this argument will be called if and only if one of the functions receive_message/5 or process_received_message/5 was called with the Extra argument different than ignore_extra.

DATA TYPES

action_request() = #'ActionRequest'{}
action_reply() = #'ActionReply'{}
error_desc() = #'ErrorDescriptor'{}
segment_no() = integer()

conn_handle() = #megaco_conn_handle{}

The record initially returned by megaco:connect/4,5. It identifies a "virtual" connection and may be reused after a reconnect (disconnect + connect).

protocol_version() = integer()

Is the actual protocol version. In most cases the protocol version is retrieved from the processed message, but there are exceptions:

When handle_connect/2,3 is triggered by an explicit call to megaco:connect/4,5.

handle_disconnect/3

handle_syntax_error/3

In these cases, the ProtocolVersion default version is obtained from the static connection configuration:

megaco:conn_info(ConnHandle, protocol_version).

Summary

Types

conn_handle()

megaco_timer()

receive_handle()

Callbacks

handle_connect(ConnHandle, ProtocolVersion)

Equivalent to handle_connect/3.

handle_connect(ConnHandle, ProtocolVersion, Extra)

Invoked when a new connection is established

handle_disconnect(ConnHandle, ProtocolVersion, Reason)

Invoked when a connection is teared down

handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr)

Equivalent to handle_message_error/4.

handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr, Extra)

Invoked when a received message just contains an error instead of a list of transactions.

handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl)

Equivalent to handle_segment_reply/6.

handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl, Extra)

This function is called when a segment reply has been received if the segment_reply_ind config option has been set to true.

handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED)

Equivalent to handle_syntax_error/4.

handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED, Extra)

Invoked when a received message had syntax errors

handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData)

Equivalent to handle_trans_ack/5.

handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData, Extra)

Optionally invoked for a transaction acknowledgement

handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData)

Equivalent to handle_trans_long_request/4.

handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData, Extra)

Optionally invoked for a time consuming transaction request

handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData)

Equivalent to handle_trans_reply/5.

handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData, Extra)

Optionally invoked for a transaction reply

handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests)

Equivalent to handle_trans_request/4.

handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests, Extra)

Invoked for each transaction request

handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid)

Equivalent to handle_trans_request_abort/5.

handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid, Extra)

Invoked when a transaction request has been aborted

handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans)

Equivalent to handle_unexpected_trans/4.

handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans, Extra)

Invoked when a unexpected message is received

Types

conn_handle()

-type conn_handle() :: #megaco_conn_handle{local_mid :: term(), remote_mid :: term()}.

megaco_timer()

-type megaco_timer() ::
          infinity |
          non_neg_integer() |
          #megaco_incr_timer{wait_for :: term(),
                             factor :: term(),
                             incr :: term(),
                             max_retries :: term()}.

receive_handle()

-type receive_handle() ::
          #megaco_receive_handle{local_mid :: term(),
                                 encoding_mod :: term(),
                                 encoding_config :: term(),
                                 send_mod :: term(),
                                 protocol_version :: term()}.

Callbacks

handle_connect(ConnHandle, ProtocolVersion)

(optional)

-callback handle_connect(ConnHandle, ProtocolVersion) -> ok | error | {error, ErrorDescr}
                            when
                                ConnHandle :: conn_handle(),
                                ProtocolVersion :: megaco_encoder:protocol_version(),
                                ErrorDescr :: megaco_encoder:error_desc().

Equivalent to handle_connect/3.

handle_connect(ConnHandle, ProtocolVersion, Extra)

(optional)

-callback handle_connect(ConnHandle, ProtocolVersion, Extra) -> ok | error | {error, ErrorDescr}
                            when
                                ConnHandle :: conn_handle(),
                                ProtocolVersion :: megaco_encoder:protocol_version(),
                                Extra :: term(),
                                ErrorDescr :: megaco_encoder:error_desc().

Invoked when a new connection is established

Connections may either be established by an explicit call to megaco:connect/4 or implicitly at the first invocation of megaco:receive_message/3.

Normally a Media Gateway (MG) connects explicitly while a Media Gateway Controller (MGC) connects implicitly.

At the Media Gateway Controller (MGC) side it is possible to reject a connection request (and send a message error reply to the gateway) by returning {error, ErrorDescr} or simply error which generates an error descriptor with code 402 (unauthorized) and reason "Connection refused by user" (this is also the case for all unknown results, such as exit signals or throw).

See note above about the Extra argument in handle_message_error/4.

handle_connect/3 (with Extra) can also be called as a result of a call to the megaco:connect/5 function (if that function is called with the Extra argument different than ignore_extra.

handle_disconnect(ConnHandle, ProtocolVersion, Reason)

(optional)

-callback handle_disconnect(ConnHandle, ProtocolVersion, Reason) -> megaco:void()
                               when
                                   ConnHandle :: conn_handle(),
                                   ProtocolVersion :: megaco_encoder:protocol_version(),
                                   Reason :: term().

Invoked when a connection is teared down

The disconnect may either be made explicitly by a call to megaco:disconnect/2 or implicitly when the control process of the connection dies.

handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr)

(optional)

-callback handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr) -> megaco:void()
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      ErrorDescr :: megaco_encoder:error_desc().

Equivalent to handle_message_error/4.

handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr, Extra)

(optional)

-callback handle_message_error(ConnHandle, ProtocolVersion, ErrorDescr, Extra) -> megaco:void()
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      ErrorDescr :: megaco_encoder:error_desc(),
                                      Extra :: term().

Invoked when a received message just contains an error instead of a list of transactions.

Incoming messages is delivered by megaco:receive_message/4 and successfully decoded. Normally a message contains a list of transactions, but it may instead contain an ErrorDescriptor on top level of the message.

Message errors are detected remotely on the other side of the protocol. And you probably don't want to reply to it, but it may indicate that you have outstanding transactions that not will get any response (request -> reply; reply -> ack).

See note above about the Extra argument in handle_message_error/4.

handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl)

(optional)

-callback handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl) -> ok
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      TransNo :: integer(),
                                      SegNo :: integer(),
                                      SegCompl :: asn1_NOVALUE | 'NULL'.

Equivalent to handle_segment_reply/6.

handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl, Extra)

(optional)

-callback handle_segment_reply(ConnHandle, ProtocolVersion, TransNo, SegNo, SegCompl, Extra) -> ok
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      TransNo :: integer(),
                                      SegNo :: megaco_encoder:segment_no(),
                                      SegCompl :: asn1_NOVALUE | 'NULL',
                                      Extra :: term().

This function is called when a segment reply has been received if the segment_reply_ind config option has been set to true.

This is in effect a progress report.

See note above about the Extra argument in handle_segment_reply/6.

handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED)

(optional)

-callback handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED) ->
                                 reply | {reply, ED} | no_reply | {no_reply, ED}
                                 when
                                     ReceiveHandle :: receive_handle(),
                                     ProtocolVersion :: megaco_encoder:protocol_version(),
                                     DefaultED :: megaco_encoder:error_desc(),
                                     ED :: megaco_encoder:error_desc().

Equivalent to handle_syntax_error/4.

handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED, Extra)

(optional)

-callback handle_syntax_error(ReceiveHandle, ProtocolVersion, DefaultED, Extra) ->
                                 reply | {reply, ED} | no_reply | {no_reply, ED}
                                 when
                                     ReceiveHandle :: receive_handle(),
                                     ProtocolVersion :: megaco_encoder:protocol_version(),
                                     DefaultED :: megaco_encoder:error_desc(),
                                     ED :: megaco_encoder:error_desc(),
                                     Extra :: term().

Invoked when a received message had syntax errors

Incoming messages is delivered by megaco:receive_message/4 and normally decoded successfully. But if the decoding failed this function is called in order to decide if the originator should get a reply message (reply) or if the reply silently should be discarded (no_reply).

Syntax errors are detected locally on this side of the protocol and may have many causes, e.g. a malfunctioning transport layer, wrong encoder/decoder selected, bad configuration of the selected encoder/decoder etc.

The error descriptor defaults to DefaultED, but can be overridden with an alternate one by returning {reply,ED} or {no_reply,ED} instead of reply and no_reply respectively.

Any other return values (including exit signals or throw) and the DefaultED will be used.

See note above about the Extra argument in handle_syntax_error/4.

handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData)

(optional)

-callback handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData) -> ok
                              when
                                  ConnHandle :: conn_handle(),
                                  ProtocolVersion :: megaco_encoder:protocol_version(),
                                  AckStatus :: ok | {error, Reason},
                                  AckData :: term(),
                                  Reason :: UserCancelReason | SendReason | OtherReason,
                                  UserCancelReason :: {user_cancel, ReasonForUserCancel},
                                  ReasonForUserCancel :: term(),
                                  SendReason :: SendCancelledReason | SendFailedReason,
                                  SendCancelledReason :: {send_message_cancelled, ReasonForSendCancel},
                                  ReasonForSendCancel :: term(),
                                  SendFailedReason :: {send_message_failed, ReasonForSendFailure},
                                  ReasonForSendFailure :: term(),
                                  OtherReason :: term().

Equivalent to handle_trans_ack/5.

handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData, Extra)

(optional)

-callback handle_trans_ack(ConnHandle, ProtocolVersion, AckStatus, AckData, Extra) -> ok
                              when
                                  ConnHandle :: conn_handle(),
                                  ProtocolVersion :: megaco_encoder:protocol_version(),
                                  AckStatus :: ok | {error, Reason},
                                  AckData :: term(),
                                  Extra :: term(),
                                  Reason :: UserCancelReason | SendReason | OtherReason,
                                  UserCancelReason :: {user_cancel, ReasonForUserCancel},
                                  ReasonForUserCancel :: term(),
                                  SendReason :: SendCancelledReason | SendFailedReason,
                                  SendCancelledReason :: {send_message_cancelled, ReasonForSendCancel},
                                  ReasonForSendCancel :: term(),
                                  SendFailedReason :: {send_message_failed, ReasonForSendFailure},
                                  ReasonForSendFailure :: term(),
                                  OtherReason :: term().

Optionally invoked for a transaction acknowledgement

If this function gets invoked or not, is controlled by the reply from the preceding call to handle_trans_request/3. The handle_trans_request/3 function may decide to return {handle_ack, ack_data()} or {handle_sloppy_ack, ack_data()} meaning that you need an immediate acknowledgement of the reply and that this function should be invoked to handle the acknowledgement.

The ack_data() argument to this function is the Erlang term returned by handle_trans_request/3.

If the AckStatus is ok, it is indicating that this is a true acknowledgement of the transaction reply.

If the AckStatus is {error, Reason}, it is an indication that the acknowledgement or even the reply (for which this is an acknowledgement) was not delivered, but there is no point in waiting any longer for it to arrive. This happens when:

reply_timer - The reply_timer eventually times out.

reply send failure - When megaco fails to send the reply (see handle_trans_reply), for whatever reason.

cancel - The user has explicitly cancelled the wait (megaco:cancel/2).

See note above about the Extra argument in handle_trans_ack/5.

handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData)

(optional)

-callback handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData) -> Reply
                                       when
                                           ConnHandle :: conn_handle(),
                                           ProtocolVersion :: megaco_encoder:protocol_version(),
                                           ReqData :: term(),
                                           Reply ::
                                               {AckAction, ActualReply} |
                                               {AckAction, ActualReply, SendOptions},
                                           AckAction ::
                                               discard_ack |
                                               {handle_ack, AckData} |
                                               {handle_sloppy_ack, AckData},
                                           ActualReply ::
                                               [megaco_encoder:action_reply()] | megaco_encoder:error_desc(),
                                           AckData :: term(),
                                           SendOptions :: [SendOption],
                                           SendOption ::
                                               {reply_timer, megaco_timer()} |
                                               {send_handle, term()} |
                                               {protocol_version, megaco_encoder:protocol_version()}.

Equivalent to handle_trans_long_request/4.

handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData, Extra)

(optional)

-callback handle_trans_long_request(ConnHandle, ProtocolVersion, ReqData, Extra) -> Reply
                                       when
                                           ConnHandle :: conn_handle(),
                                           ProtocolVersion :: megaco_encoder:protocol_version(),
                                           ReqData :: term(),
                                           Extra :: term(),
                                           Reply ::
                                               {AckAction, ActualReply} |
                                               {AckAction, ActualReply, SendOptions},
                                           AckAction ::
                                               discard_ack |
                                               {handle_ack, AckData} |
                                               {handle_sloppy_ack, AckData},
                                           ActualReply ::
                                               [megaco_encoder:action_reply()] | megaco_encoder:error_desc(),
                                           AckData :: term(),
                                           SendOptions :: [SendOption],
                                           SendOption ::
                                               {reply_timer, megaco_timer()} |
                                               {send_handle, term()} |
                                               {protocol_version, megaco_encoder:protocol_version()}.

Optionally invoked for a time consuming transaction request

If this function gets invoked or not is controlled by the reply from the preceding call to handle_trans_request/3. The handle_trans_request/3 function may decide to process the action requests itself or to delegate the processing to this function.

The req_data() argument to this function is the Erlang term returned by handle_trans_request/3.

Any other return values (including exit signals or throw) will result in an error descriptor with code 500 (internal gateway error) and the module name (of the callback module) as reason.

See note above about the Extra argument in handle_trans_long_request/4.

handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData)

(optional)

-callback handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData) -> ok
                                when
                                    ConnHandle :: conn_handle(),
                                    ProtocolVersion :: megaco_encoder:protocol_version(),
                                    UserReply :: Success | Failure,
                                    ReplyData :: term(),
                                    Success :: {ok, Result},
                                    Result :: TransactionResult | SegmentResult,
                                    TransactionResult :: [megaco_encoder:action_reply()],
                                    SegmentResult ::
                                        {megaco_encoder:segment_no(),
                                         LastSegment,
                                         [megaco_encoder:action_reply()]},
                                    Failure :: {error, Reason} | {error, ReplyNo, Reason},
                                    Reason ::
                                        TransactionReason | SegmentReason | UserCancelReason | SendReason |
                                        OtherReason,
                                    TransactionReason :: megaco_encoder:error_desc(),
                                    SegmentReason ::
                                        {megaco_encoder:segment_no(),
                                         LastSegment,
                                         megaco_encoder:error_desc()},
                                    OtherReason ::
                                        timeout |
                                        {segment_timeout, MissingSegments} |
                                        exceeded_recv_pending_limit |
                                        term(),
                                    LastSegment :: boolean(),
                                    MissingSegments :: [megaco_encoder:segment_no()],
                                    UserCancelReason :: {user_cancel, ReasonForUserCancel},
                                    ReasonForUserCancel :: term(),
                                    SendReason :: SendCancelledReason | SendFailedReason,
                                    SendCancelledReason :: {send_message_cancelled, ReasonForSendCancel},
                                    ReasonForSendCancel :: term(),
                                    SendFailedReason :: {send_message_failed, ReasonForSendFailure},
                                    ReasonForSendFailure :: term(),
                                    ReplyNo :: pos_integer().

Equivalent to handle_trans_reply/5.

handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData, Extra)

(optional)

-callback handle_trans_reply(ConnHandle, ProtocolVersion, UserReply, ReplyData, Extra) -> ok
                                when
                                    ConnHandle :: conn_handle(),
                                    ProtocolVersion :: megaco_encoder:protocol_version(),
                                    UserReply :: Success | Failure,
                                    ReplyData :: term(),
                                    Extra :: term(),
                                    Success :: {ok, Result},
                                    Result :: TransactionResult | SegmentResult,
                                    TransactionResult :: [megaco_encoder:action_reply()],
                                    SegmentResult ::
                                        {megaco_encoder:segment_no(),
                                         LastSegment,
                                         [megaco_encoder:action_reply()]},
                                    Failure :: {error, Reason} | {error, ReplyNo, Reason},
                                    Reason ::
                                        TransactionReason | SegmentReason | UserCancelReason | SendReason |
                                        OtherReason,
                                    TransactionReason :: megaco_encoder:error_desc(),
                                    SegmentReason ::
                                        {megaco_encoder:segment_no(),
                                         LastSegment,
                                         megaco_encoder:error_desc()},
                                    OtherReason ::
                                        timeout |
                                        {segment_timeout, MissingSegments} |
                                        exceeded_recv_pending_limit |
                                        term(),
                                    LastSegment :: boolean(),
                                    MissingSegments :: [megaco_encoder:segment_no()],
                                    UserCancelReason :: {user_cancel, ReasonForUserCancel},
                                    ReasonForUserCancel :: term(),
                                    SendReason :: SendCancelledReason | SendFailedReason,
                                    SendCancelledReason :: {send_message_cancelled, ReasonForSendCancel},
                                    ReasonForSendCancel :: term(),
                                    SendFailedReason :: {send_message_failed, ReasonForSendFailure},
                                    ReasonForSendFailure :: term(),
                                    ReplyNo :: pos_integer().

Optionally invoked for a transaction reply

The sender of a transaction request has the option of deciding, whether the originating Erlang process should synchronously wait (megaco:call/3) for a reply or if the message should be sent asynchronously (megaco:cast/3) and the processing of the reply should be delegated this callback function.

Note that if the reply is segmented (split into several smaller messages; segments), then some extra info, segment number and an indication if all segments of a reply has been received or not, is also included in the UserReply.

The ReplyData defaults to megaco:lookup(ConnHandle, reply_data), but may be explicitly overridden by a megaco:cast/3 option in order to forward info about the calling context of the originating process.

At success(), the UserReply either contains:

A list of 'ActionReply' records possibly containing error indications.

A tuple of size three containing: the segment number, the last segment indicator and finally a list of 'ActionReply' records possibly containing error indications. This is of course only possible if the reply was segmented.

failure() indicates an local or external error and can be one of the following:

A transaction_reason(), indicates that the remote user has replied with an explicit transactionError.

A segment_reason(), indicates that the remote user has replied with an explicit transactionError for this segment. This is of course only possible if the reply was segmented.

A user_cancel_reason(), indicates that the request has been canceled by the user. reason_for_user_cancel() is the reason given in the call to the cancel function.

A send_reason(), indicates that the transport module send_message function did not send the message. The reason for this can be:

send_cancelled_reason() - the message sending was deliberately cancelled. reason_for_send_cancel() is the reason given in the cancel return from the send_message function.

send_failed_reason() - an error occurred while attempting to send the message.

An other_reason(), indicates some other error such as:

timeout - the reply failed to arrive before the request timer expired.

{segment_timeout, missing_segments()} - one or more segments was not delivered before the expire of the segment timer.

exceeded_recv_pending_limit - the pending limit was exceeded for this request.

See note above about the Extra argument in handle_trans_reply/5.

handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests)

(optional)

-callback handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests) ->
                                  Pending | Reply | ignore_trans_request
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      ActionRequests :: [megaco_encoder:action_request()],
                                      Pending :: {pending, ReqData},
                                      ReqData :: term(),
                                      Reply ::
                                          {AckAction, ActualReply} | {AckAction, ActualReply, SendOptions},
                                      AckAction ::
                                          discard_ack |
                                          {handle_ack, AckData} |
                                          {handle_pending_ack, AckData} |
                                          {handle_sloppy_ack, AckData},
                                      ActualReply ::
                                          [megaco_encoder:action_reply()] | megaco_encoder:error_desc(),
                                      AckData :: term(),
                                      SendOptions :: [SendOption],
                                      SendOption ::
                                          {reply_timer, megaco_timer()} |
                                          {send_handle, term()} |
                                          {protocol_version, integer()}.

Equivalent to handle_trans_request/4.

handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests, Extra)

(optional)

-callback handle_trans_request(ConnHandle, ProtocolVersion, ActionRequests, Extra) ->
                                  Pending | Reply | ignore_trans_request
                                  when
                                      ConnHandle :: conn_handle(),
                                      ProtocolVersion :: megaco_encoder:protocol_version(),
                                      ActionRequests :: [megaco_encoder:action_request()],
                                      Extra :: term(),
                                      Pending :: {pending, ReqData},
                                      ReqData :: term(),
                                      Reply ::
                                          {AckAction, ActualReply} | {AckAction, ActualReply, SendOptions},
                                      AckAction ::
                                          discard_ack |
                                          {handle_ack, AckData} |
                                          {handle_pending_ack, AckData} |
                                          {handle_sloppy_ack, AckData},
                                      ActualReply ::
                                          [megaco_encoder:action_reply()] | megaco_encoder:error_desc(),
                                      AckData :: term(),
                                      SendOptions :: [SendOption],
                                      SendOption ::
                                          {reply_timer, megaco_timer()} |
                                          {send_handle, term()} |
                                          {protocol_version, integer()}.

Invoked for each transaction request

Incoming messages is delivered by megaco:receive_message/4 and successfully decoded. Normally a message contains a list of transactions and this function is invoked for each TransactionRequest in the message.

This function takes a list of 'ActionRequest' records and has three main options:

Return ignore_trans_request - Decide that these action requests shall be ignored completely.

Return pending() - Decide that the processing of these action requests will take a long time and that the originator should get an immediate 'TransactionPending' reply as interim response. The actual processing of these action requests instead should be delegated to the the handle_trans_long_request/3 callback function with the req_data() as one of its arguments.

Return reply() - Process the action requests and either return an error_descr() indicating some fatal error or a list of action replies (wildcarded or not).

If for some reason megaco is unable to deliver the reply, the reason for this will be passed to the user via a call to the callback function handle_trans_ack, unless ack_action() = discard_ack.

The ack_action() is either:

discard_ack - Meaning that you don't care if the reply is acknowledged or not.

{handle_ack, ack_data()} | {handle_ack, ack_data(), send_options()} - Meaning that you want an immediate acknowledgement when the other part receives this transaction reply. When the acknowledgement eventually is received, the handle_trans_ack/4 callback function will be invoked with the ack_data() as one of its arguments. ack_data() may be any Erlang term.

{handle_pending_ack, ack_data()} | {handle_pending_ack, ack_data(), send_options()} - This has the same effect as the above, if and only if megaco has sent at least one pending message for this request (during the processing of the request). If no pending message has been sent, then immediate acknowledgement will not be requested.

Note that this only works as specified if the sent_pending_limit config option has been set to an integer value.

{handle_sloppy_ack, ack_data()}| {handle_sloppy_ack, ack_data(), send_options()} - Meaning that you want an acknowledgement sometime. When the acknowledgement eventually is received, the handle_trans_ack/4 callback function will be invoked with the ack_data() as one of its arguments. ack_data() may be any Erlang term.

Any other return values (including exit signals or throw) will result in an error descriptor with code 500 (internal gateway error) and the module name (of the callback module) as reason.

See note above about the Extra argument in handle_trans_request/4.

handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid)

(optional)

-callback handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid) -> ok
                                        when
                                            ConnHandle :: conn_handle(),
                                            ProtocolVersion :: megaco_encoder:protocol_version(),
                                            TransNo :: integer(),
                                            Pid :: undefined | pid().

Equivalent to handle_trans_request_abort/5.

handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid, Extra)

(optional)

-callback handle_trans_request_abort(ConnHandle, ProtocolVersion, TransNo, Pid, Extra) -> ok
                                        when
                                            ConnHandle :: conn_handle(),
                                            ProtocolVersion :: megaco_encoder:protocol_version(),
                                            TransNo :: integer(),
                                            Pid :: undefined | pid(),
                                            Extra :: term().

Invoked when a transaction request has been aborted

This function is invoked if the originating pending limit has been exceeded. This usually means that a request has taken abnormally long time to complete.

See note above about the Extra argument in handle_trans_request_abort/5.

handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans)

(optional)

-callback handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans) -> ok
                                     when
                                         ConnHandle :: conn_handle(),
                                         ProtocolVersion :: megaco_encoder:protocol_version(),
                                         Trans ::
                                             megaco_encoder:transaction_pending() |
                                             megaco_encoder:transaction_reply() |
                                             megaco_encoder:transaction_response_ack().

Equivalent to handle_unexpected_trans/4.

handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans, Extra)

(optional)

-callback handle_unexpected_trans(ConnHandle, ProtocolVersion, Trans, Extra) -> ok
                                     when
                                         ConnHandle :: conn_handle(),
                                         ProtocolVersion :: megaco_encoder:protocol_version(),
                                         Trans ::
                                             megaco_encoder:transaction_pending() |
                                             megaco_encoder:transaction_reply() |
                                             megaco_encoder:transaction_response_ack(),
                                         Extra :: term().

Invoked when a unexpected message is received

If a reply to a request is not received in time, the megaco stack removes all info about the request from its tables. If a reply should arrive after this has been done the app has no way of knowing where to send this message. The message is delivered to the "user" by calling this function on the local node (the node which has the link).

See note above about the Extra argument in handle_unexpected_trans/4.