Jasmin

Published on December 2020 | Categories: Documents | Downloads: 4 | Comments: 0 | Views: 66
of 101
Download PDF   Embed   Report

Comments

Content

 

Jasmin Documentatio Documentation n Release 0.9.3-beta 

Jookies LTD

April 24, 2016

 

Contents

1

Feat Fe atur ures es

2

Gettin Get ting g sta starte rted d

3

Fulll con Ful conten tents ts   3.1 Arc Archit hitect ecture ure ov overv ervie iew w . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 3.2 Su Sup ppo porrt   . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3. 3.3 3 3.4 3.4 3.5 5 3. 3.6 3.7 3.7 3.8 3.9 3.10 3.11 1 3.1 3.12 3.1 3.13 3 3.14

Instal Inst alla lati tion on   . . . . . . . . . HTTP HT TP AP APII   . . . . . . . . . SMPP SM PP Se Serv rver er AP APII   . . . . . The me messa ssage ge rou router ter   . . . . . Inte In terc rcep epti tion on   . . . . . . . . . Progra Pro gramm mming ing ex examp amples les   . . Manage Man ageme ment nt CLI ov overv ervie iew w  Manageme Mana gement nt CLI Modul Modules es   . Billin Bil ling g . . . . . . . . . . . Messaging Mess aging flow flowss   . . . . . . Userr FAQ   . . . . . . . . . . Use Develope Dev eloperr FAQ AQ   . . . . . . .

4

Links

5

Lice Li cens nsee

 

3  

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .  

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

5

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

. . . . . . . . . . . .

7 7 8

8 14 27 29 35 42 44 50 77 83 86 87 95

 

97

i

 

ii

 

Jasmin Documentation, Release 0.9.3-beta

Jasmin  is an open-source SMS Gateway with many enterprise-class features, Jasmin is built to be easily customized Jasmin is to meet the specific needs of messaging exchange growing business. Based on strong message routing algorithms, Jasmin provides flexibility to define rule based routing based on various criteria: sender ID, source, destination and many combinations. combinations. Auto reconnection and re-routi re-routing ng mechanism managing peak hours or link failover for high availability services. Jasmin is written in Python and Twisted framework for serving highly scalable applications, SMS message delivery can be done through HTTP and SMPP protocols, intelligent routing can be configured in real-time through an API, cli interface or a web backend. Web backend is written in Django  1 and is providing advanced tools for managing and monitoring the gateway.

1

Web interface will come in v0.7

Contents

1

 

Jasmin Documentation, Release 0.9.3-beta

2

Contents

 

CHAPTER 1

Features

• SMPP Cl Client ient / Server Server • HTTP Cl Client ient / Serve Serverr • Based on AMQP broker ffor or store&forward store&forward mechanisms • Advanced m message essage routing routing : Simple & static, static,  Roundrobin,  Failover ,  Leastcost  ..  .. • Standard message filtering: TransparentFilter ,   ConnectorFilter ,  UserFilter  ..  .. • Advanced message filtering: filtering:   EvalPyFilter  • Flexible billing support • Web ui for management management • Supports Unicode (UT (UTF-8 F-8 / 16) for sending out multilingual multilingual SMS SMS • Supports easy creation and sending of specialized/bina specialized/binary ry SMS like mono Ringtones, W WAP AP Push, Vcards • Supports concate concatenated nated (multipa (multipart) rt) SMS contents (long (long SMS) Jasmin is designed for  performance,  high traffic loads  and  full in-memory execution.

3

 

Jasmin Documentation, Release 0.9.3-beta

4

Chapter 1. Features

 

CHAPTER 2

Getting started

•   Installation Installation –  – Install and run Jasmin SMS Gateway  – Basic push/pull SMS application via HTTP •  Receiving SMS  – •   HTTP API API –  – HTTP API technical specification •  SMPP Server API API –  – SMPP Server API technical specification •   Routing – Running basic SMS and routing scenarios FAQ –  – Frequently asked questions •   User FAQ

5

 

Jasmin Documentation, Release 0.9.3-beta

6

Chapter 2. Getting started

 

CHAPTER 3

Full contents

3.1 Arc Architect hitecture ure overview overview Jasmin is Jasmin  is composed of several components with scoped responsibilities:

Fig. 3.1: Jasmin SMS Gatew Gateway ay high le level vel desig design n

1.   jCli: Telnet management console, refer to Management to  Management CLI overvie overview w for more details,

7

 

Jasmin Documentation, Release 0.9.3-beta

PerspectBroker er providing  providing facilities to manage (add, remove, list, start, stop ...) 2.  SMPP Client Manager PB: A   PerspectBrok SMPP client connectors, 3.   Router: A  PerspectBroker  PerspectBroker   providing facilities to manage message routes, groups, users, http connectors and filters, 4.   DLR Thrower: A serv service ice for deli deliver vering ing ackn acknowle owledgem dgement ent receipts receipts back to third third part party y appli applicati cations ons through HTTP, refer to HTTP to HTTP API for API  for more details, 5.   DeliverSM Thrower: A service for delivering MO SMS (Mobile originated) to third party applications through HTTP, refer to HTTP to HTTP API for API  for more details, 6.  HTTP API: A HTTP Server to be used by third party application to send MT SMS (Mobile Terminated), refer  HTTP API for to to HTTP API  for more details. 7.   SMPP Server API: A SMPP Server to be used by third party application to send and receive SMS through a stateful tcp protocol, refer to SMPP to  SMPP Server API API for  for more details. Jasmin core and its external connectors (used for AMQP, Redis, SMPP, SMPP, HTTP, Telnet Telnet ...) are written in Python and are matrix,,  a event-d event-driven riven networking engine. mainly based on Twisted on Twisted matrix

3.2 Sup Support port 3.2.1 Getting Help The easiest way to get help with the project is to open an issue on  Github  Github..  forum is  is also available for support. The forum The

3.2.2 Commer Commercial cial Support Support We offer commercial support for Jasmin for  Jasmin,,  commercial solution hosting, as well as remote and on-site consulting and engineering. [email protected] nsms.com to  to learn more, or visit us at  http://jooki http://jookies.net es.net.. You can contact us at  at support@jasmi

3.3 Instal Installation lation The Installation section is intended to get you up and running quickly with a simple SMS sending scenario through HTTP API or  SMPP Server API API.. API or SMPP Jasmin installation is provided as rpm & deb Linux packages, docker image and pypi package. Important:   Jasmin Jasmin needs needs a worki working ng   RabbitMQ   and  Redis  servers, more info in  Prerequisites & Dependencies below.

Prerequisites uisites & Dependencie Dependencies s 3.3.1 Prereq Jasmin requires Jasmin  requires Python 2.7 or newer (but not Python 3) with a functioning pip functioning  pip module. module.

8

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

module install installation: ation: #  curl https://bootstrap.pypa.io/get-pip.py | python Hint:   Latest pip module Depending on the Linux distribution you are using, you may need to install the following dependencies: Server,,  Ubuntu package name:   rabbitmq-server. Rabbi RabbitMQ tMQ is used heavily by Jasmi Jasmin n as its core •  RabbitMQ Server AMQP. •   Redis Server Server, ,   Ubuntu package name: receiving receivin g deliver delivery y receipts.

  redis-server

. Redis is used mainly mainly for mappi mapping ng message message ID’s when

• header files and a sta static tic library for Python, Python, Ubuntu package name: name:  python-dev • Foreign Function Interf Interface ace library (development (development files), Ubuntu package name:  libffi-dev • Secure Sockets Layer toolk toolkit it - developme development nt files, Ubuntu package name:  libssl-dev •   Twisted Matrix Matrix,, Python Event-driven networking engine, Ubuntu package name:   python-twisted python-twisted

3.3.2 Ubun Ubuntu tu Jasmin can Jasmin  can be installed through  DEB  packages hosted on Packagecloud on Packagecloud:: wget -qO - http:/ wget http://bi /bit.l t.ly/j y/jasm asminin-deb deb-re -repo po | sud sudo o bas bash h sudo apt-g apt-get et install install python-ja python-jasmin smin

versions are supported. Note:   Ubuntu 15.04 and higher versions Once Jasmin installed, you may simply start the jasmind service: sudo syste systemctl mctl enab enable le jasmi jasmind nd sudo systemctl systemctl start start jasm jasmind ind

Note:   redis and rabbitmq must be started started with jasmin.

3.3.3 RHEL & CentOS CentOS Jasmin can Jasmin  can be installed through  RPM  packages hosted on Packagecloud on  Packagecloud:: wget -qO - http:/ wget http://bi /bit.l t.ly/j y/jasm asminin-rpm rpm-re -repo po | sud sudo o bas bash h sudo yum install install python-jas python-jasmin min

Note:   Red Hat Enterprise Linux Linux 7 & CentOS 7 are supported. supported.

You may get the following error if  RabbitMQ   RabbitMQ or  Redis server are not installed: No pac packag kage e red redis is availa available ble. . No packa package ge rabbitmq-s rabbitmq-serve erver r avai available lable. .

These requirements are available from the EPEL the  EPEL repository, repository,  you’ll need to enable it before installing Jasmin:

3.3. Installation

9

 

Jasmin Documentation, Release 0.9.3-beta

## RHE RHEL/C L/Cent entOS OS 7 64-Bit 64-Bit ## yum -y install https://dl.fedoraproject.org/pub https://dl.fedoraproject.org/pub/epel/epel-releas /epel/epel-release-latest-7.noarch e-latest-7.noarch.rpm .rpm

Once Jasmin installed, you may simply start the jasmind service: sudo syste systemctl mctl enab enable le jasmi jasmind nd sudo systemctl systemctl start start jasm jasmind ind

Note:   redis and rabbitmq must be started started with jasmin.

3.3.4 Pyp 3.3.4 Pypii Having another OS not covered by package installations described above ? using the Python package installer will be possible, you may have to follow these instructions:

System user Jasmin system service is running under the  jasmin system user, you will have to create this user under  jasmin group: sudo sud o use userad radd d jas jasmin min

System folders In order to run as a POSIX system service, Jasmin requires the creation of the following folders before installation: /etc/jasmin /etc/jasmin/resource /etc /etc/ /jas jasmin min/sto /stor re /var/log/jasmin

#> Must ust be owne wned by jas jasmin min user user #> Must be owned by jasmin user

Installation The last step is to install jasmin through pip through  pip:: sudo sud o pip instal install l jas jasmin min

Once Jasmin installed, execute the following steps to start Jasmin as a system service: # On sudo # On sudo

ubun ubuntu tu: : wget http http://bi ://bit.ly/ t.ly/jasm jasmind-u ind-ubuntu buntu -O /etc/ /etc/init. init.d/ja d/jasmind smind red redhat hat, , cen centos tos: : wget http http://bi ://bit.ly/ t.ly/jasm jasmind-r ind-redhat edhat -O /etc/ /etc/init. init.d/ja d/jasmind smind

# Then Then: : sudo chmod +x /etc/init. /etc/init.d/ja d/jasmind smind sudo updat update-rc e-rc.d .d jasmind jasmind defau defaults lts sudo invok invoke-rc e-rc.d .d jasmind jasmind start

Note:   On some Linux distributions, distributions, you may use use sudo systemctl enable jasmind.

10

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

started with jasmin. Note:   redis and rabbitmq must be started

3.3.5 Dock Docker er You probably have heard of   Docker, Docker,  it is a contain container er technology technology with a ton of momentum. momentum. But if you haven’t haven’t,, you can think of containers as easily-configured, lightweight VMs that start up fast, often in under one second. Containers are ideal for microservice for  microservice architectures  and for environments that scale rapidly or release often, Here’s more from Docker’s website. website.

Installing Docker Before we get into containers, we’ll need to get Docker running locally. You can do this by installing the package for here). ). Running a Mac? You’ll need to install the boot2docker the  boot2docker application application before  before your system (tip: you can find yours find  yours here using Docker. Once that’s set up, you’re ready to start using Jasmin container !

Pulling Jasmin image This command will pull latest jasmin docker image to your computer: docker docke r pull jook jookies/j ies/jasmi asmin n

You should have Jasmin image listed in your local docker images: # doc docker ker images images REPOSITORY jasmin

TAG latest

IMAGE ID 0e4cf8879899

CREATED 36 minutes ago

VIRTUAL SIZE 478.6 MB

Note:   The Jasmin docker image is a self-contained/standalone self-contained/standalone box including Jasmin+Redis+Rab Jasmin+Redis+RabbitMQ. bitMQ.

Starting Jasmin in a conta container iner This command will create a new docker container with name  jasmin_01 which run as a demon: docker doc ker run -d -p 1401:1 1401:1401 401 -p 277 2775:2 5:2775 775 -p 899 8990:8 0:8990 990 --n --name ame jas jasmin min_01 _01 joo jookie kies/j s/jasm asmin: in:lat latest est

Note that we used the parameter  -p  three times, it defines port forwarding from host computer to the container, typing -p 2775:2775  will map the container’s 2775 port to your host 2775 port; this can be useful in case you’ll be running multiple containers of Jasmin where you keep a port offset of 10 between each, example: docker run -d -p 1411:1 docker 1411:1401 401 -p 278 2785:2 5:2775 775 -p 899 8990:8 0:8990 990 --n --name ame jas jasmin min_02 _02 joo jookie kies/j s/jasm asmin: in:lat latest est docker doc ker run -d -p 1421:1 1421:1401 401 -p 279 2795:2 5:2775 775 -p 900 9000:8 0:8990 990 --n --name ame jas jasmin min_03 _03 joo jookie kies/j s/jasm asmin: in:lat latest est docker doc ker run -d -p 1431:1 1431:1401 401 -p 280 2805:2 5:2775 775 -p 901 9010:8 0:8990 990 --n --name ame jas jasmin min_04 _04 joo jookie kies/j s/jasm asmin: in:lat latest est

You should have the container running by typing the following: # dock docker er ps CONTAINER ID 0a2f 0a2faf afbe be60 60d0 d0

IMAGE jook jookie ies/ s/ja jasm smin in:l :lat ates est t

COMMAND "/do "/dock cker er-e -ent ntry rypo poin int. t.

CREATED 43 minu minute tes s a ago go

STATUS Up 41 minu minute tes s

And in order to control the container  jasmin_01, use:

3.3. Installation

11

PORTS 0.0. 0.0.0. 0.0: 0:

 

Jasmin Documentation, Release 0.9.3-beta

docker stop jasm docker jasmin_01 in_01 docker docke r star start t jasmin_01 jasmin_01

It’s possible to access log files located in  /var/log/jasmin /var/log/jasmin inside the container by mounting it as a shared folder: docker docke r run -d -v /home/user /home/user/jas /jasmin_l min_logs:/ ogs:/var/ var/log/j log/jasmin asmin --nam --name e jasm jasmin_10 in_100 0 jook jookies/j ies/jasmi asmin:lat n:latest est

3.3.6 Sendin Sending g your first first SMS For the really impatient, if you want to give Jasmin a whirl right now and send your first SMS, you’ll have to connect overview and  and setup a connection to your SMS-C, let’s   assume   you have the following SMPP to Management to  Management CLI overview connection parameters as provided from your partner: Table 3.1: Basic SMPP connection parameters

Paramater Host   Port  

Description Host Host of rem emot otee SMSSMS-C C SMP SMPP P port port on remote remote SMS SMS-C -C Username   Auth Authen enti tica cati tion on user userna name me Password   Au Auth then enti tica cati tion on pass passwo word rd Throughput   Maxim Maximum um sent sent SMS/se SMS/secon cond d

Value 17 172 2.1 .16 6.1 .10. 0.67 67 277 2775 5 sm smpp ppcl clie ient nt1 1 pass passwo word rd 110

Note:   In the next sections sections we’ll be heavily heavily using jCli jCli console, console, if you feel lost, please refer refer to Management to  Management CLI overview for overview  for detailed information.

1. Adding SMPP connection Connect to jCli console through telnet (telnet 127.0.0.1 8990) using  jcliadmin/jclipwd jcliadmin/jclipwd default authentication parameters and add a new connector with an  CID=DEMO_CONNECTOR: Authentication required. Username: jcliadmin Password: Welcom Wel come e to Jasmin Jasmin consol console e Type Type help help or ? to list list comm comman ands ds. . Session Sessio n ref ref: : 2 jcli jcli : smpp smppcc ccm m -a > cid DEMO_CONNE DEMO_CONNECTOR CTOR > host 172. 172.16.10 16.10.67 .67 > port port 2775 2775 > usern username ame smppclient smppclient1 1 > pas passwo sword rd passwo password rd > submi submit_th t_through roughput put 110 > ok Successful Succe ssfully ly added connector connector [DEM [DEMO_CON O_CONNECT NECTOR] OR]

2. Starting the connector connector Let’s start the newly added connector:

12

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jcli : smp jcli smppcc pccm m -1 DEMO_C DEMO_CONN ONNECT ECTOR OR Successful Succe ssfully ly started started connector connector id:DE id:DEMO_CO MO_CONNEC NNECTOR TOR

You can check if the connector is bound to your provider by checking its log file (default to /var/log/jasmin/defaultDEMO_CONNECTOR.log) or through jCli console: jcli : smp jcli smppcc pccm m --l --list ist #Connector id #DEMO_CONNECTOR Total connectors: connectors: 1

Service Session started BOUND_TRX

Starts Stops 1 0

3. Configure simple route We’ll configure a default route to send all SMS through our newly created DEMO_CONNECTOR: jcli jcli : mtro mtrout uter er -a Addi Adding ng a new new MT Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type defa defaultro ultroute ute jasmin.routing.Routes.DefaultRout jasmin.routing.R outes.DefaultRoute e arguments: connector > conne connector ctor smpp smppc(DEM c(DEMO_CO O_CONNECT NNECTOR) OR) > rate rate 0.00 0.00 > ok Successful Succe ssfully ly added MTRoute MTRoute [Def [DefaultR aultRoute] oute] with order order:0 :0

4. Create a user In order to use Jasmin’s HTTP API to send SMS messages, you have to get a valid user account, that’s what we’re going to do below. First we have to create a group to put the new user in: jc jcli li : gr grou oup p -a Addi Adding ng a new new Grou Group: p: (ok: (ok: sa save ve, , ko: ko: exit exit) ) > gid foogro foogroup up > ok Successfu Succ essfully lly added Group [foo [foogroup group] ]

And then create the new user: jc jcli li : us user er -a Addi Adding ng a new new User User: : (ok: (ok: save save, , ko: ko: exit exit) ) > use userna rname me foo > pas passwo sword rd bar > gid foogro foogroup up > ui uid d fo foo o > ok Succes Suc cessfu sfully lly added added User User [fo [foo] o] to Gro Group up [fo [foogr ogroup oup] ]

5. Send SMS Sending outbound SMS (MT) is simply done through Jasmin’s HTTP API (refer to HTTP to HTTP API for API for detailed information about sending and receiving SMS and receipts):

3.3. Installation

13

 

Jasmin Documentation, Release 0.9.3-beta

http://127.0.0.1:1401/send?userna http://127.0.0.1 :1401/send?username=foo&password=b me=foo&password=bar&to=06222172&co ar&to=06222172&content=hello ntent=hello

Calling the above url from any brower will send an SMS to  06222172  with  hello  content, if you receive a response like the below example it means your SMS is accepted for delivery: Success "9ab2867c-96ce-4405-b890-8d35d52c8 "9ab2867c-96ce-4405-b890-8d35d52c8e01" e01"

For more troubleshooting about message delivery, you can check details in related log files in  /var/log/jasmin /var/log/jasmin: Table 3.2: Messaging related log log files

Log filename

Description

messages.log   Information about queued, rejected, receive received d and sent messages default-DEMO_CONNECTOR.log   The SMPP connector log file

HTTP P API API 3.4 HTT This document is targeted at software designers/programmers wishing to integrate SMS messaging as a function into their applications using HTTP protocol, e.g. in connection with WEB-server, unified messaging, information services etc.. API.. If you need to use a stateful tcp protocol ( SMPP v3.4), please refer to SMPP to  SMPP Server API SMS Messages can be transmitted using HTTP protocol, the following requirements must be met to enable the service: • You need a Jasmin use userr account • You need sufficient cred credit it on your Jasmin user account 1 Note:   The ABCs:

•   MT is referred to Mobile Terminated, a SMS-MT is an SMS sent to mobile •   MO is referred to Mobile Originated, a SMS-MO is an SMS sent from mobile

3.4.1 Featur Features es The ja-http API allows you to: • Send and receive SMS thr through ough Jasmin’s Jasmin’s connectors, • Receive htt http p callbacks for delivery delivery notification (receipts) when SMS-MT is received (or not) on mobile station, • Send and receive long (more than 160 characters) SMS, unicode/ unicode/binary binary content and receive http callb callbacks acks when a mobile station send you a SMS-MO. • Check your balance status, status, • Check a message rat ratee price before sending sending it. 1

14

Billing

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

3.4.2 Sendin Sending g SMS-MT SMS-MT In order to deliver  SMS-MT  messages, Data is transferred using  HTTP GET/POST  requests  requests.. The Jasmin gatewa gateway y accepts requests at the following URL: http://127.0.0.1:1401/send Note:   Host 127.0.0.1 and port 1401 are default values and configurable in /etc/jasmin/jasmin.cfg, see  jasmin.cfg / http-api.

This guide will help understand how the API works and provide  Examples  for sending SMS-MT.

HTTP request parameters When calling Jasmin’s URL from an application, the below parameters must be passed (at least mandatory ones), the api will return a message id on success, see  HTTP response. Table 3.3: ja-http sending SMS parameters parameters

Value /  Pattern

Parameter

Destination address from   Originating address

to

 

coding username password priority

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 or 14 Text (30 char. max) Text (30 char. max) 0, 1, 2 or 3

validity- Integer period dlr   yes or no dlrurl

PresExence ample(s) 20203050Mandatory 20203050,OpJasmin tional

Description / Notes

Destination address, only one address is supported per request Originating address, In case rewriting of the sender’s address is supported or permitted by the SMS-C used to transmit the message, this number is transmitted as the originating address Sets the Data Coding Scheme bits, default is 0, accepts values all allowed values in SMPP protocol  1

1

Optional

 jasmin_user  jasmin_pass 2

Manda- Username for Jasmin user account. tory Manda- Password for Jasmin user account. tory OpDefault is 0 (lowest priority) tional

1440

Optional ye s Optional HTTP(s) URL   http://host/dlr.php Mandatory if 

Message validity (minutes) to be passed to SMSC, default is value is None (message will take SMSC’s default) Default is no (no DLR will be tracked) If a DLR is requested (dlr = ‘yes’), dlr-url MUST be set, if not, dlr value is reconsidered as ‘no’

dlr 

dlrlevel

1, 2 or 3

2

Manda- 1: SMS-C level, 2: Terminal level, 3: Both tory if  dlr 

GET or POST dlrmethod

GET

Manda- DLR is transmitted through http to a third party application using tory if  GET or POST method. dlr 

content

Text

3.4. HTTP API

Hello world !

Manda- Content to be sent tory

15

 

Jasmin Documentation, Release 0.9.3-beta

HTTP response When the request is validated, a SubmitSM PDU is set up with the provided request parameters and sent to the routed connector through a AMQP queue, a queued message-id is returned: Success "07033084-5cfd-4812-90a4-e4d24ffb6 "07033084-5cfd-4812-90a4-e4d24ffb6e3d" e3d"

Otherwise, an error is returned: Error Err or "No route route found" found"

Table 3.4: HTTP response code details details

HTTP Code

HTTP Body

Meaning Mes Messag sagee is suc succes cessfu sfully lly queued queued,, messaged-id is returned Request parameters validation error

200

 

Succes Successs “07 “07033 033084 084-5c -5cfdfd-481 4812-9 2-90a4 0a4-e4 -e4d24 d24ff ffb6e b6e3d” 3d”

400

 

400 400 400 400

     

Error “Mandatory arguments not found, please refer to the HTTPAPI specifications.” Error “Argument _ is unknown.” Er Erro rorr “Ar Argu gume ment nt _ has has an in inv val alid id val alue ue:: _. _.”” Er Erro rorr “Man “Manda dato tory ry ar argu gume ment nt _ is not not fo foun und. d.”” dynamic messages  

 

Request parameters validation error Requ Reques estt para parame mete ters rs valid alidat atio ion n erro errorr Requ Reques estt para parame mete ters rs valid alidat atio ion n erro errorr Credentials validatio validation n error, c.f.  User  credentials

403 403

   

Er Erro rorr “Au Auth then enti tica cati tion on fa fail ilur uree fo forr user userna name me:_ :_”” Erro Errorr “Au Auth thor oriz izat atio ion n fa fail iled ed fo forr user userna name me:_ :_””

403

 

412 500

   

Error “Cannot charge submit_sm, check RouterPB log file for details” Error “No route found” Error “Cannot send submit_sm, check  SMPPClientManagerPB log file for details”

Au Auth then enti tica cati tion on erro errorr Cr Cred eden enti tial alss vali valida dati tion on erro errorr, c.f. c.f. User  credentials

User charging error Message routing error Fallback error, checking log file will provide better details

Examples Here is an example of how to send simple GSM 03.38 messages: Python hon exa exampl mple e # Pyt # http://jasminsms. http://jasminsms.com com

import   urllib2 import   urllib baseParams   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar', ,   'to': 'to':'+336222172' '+336222172', ,   'content': 'content':'Hello' 'Hello'} } # Sen Send d an SMS SMS-MT -MT wit with h min minima imal l par parame ameter ters s urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read() # Sen Send d an SMS SMS-MT -MT wit with h def define ined d ori origin ginati ating ng add addres ress s baseParams['from' baseParams[ 'from'] ]   =   'Jasmin 'Jasmin GW' urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read()

Here is an example of how to request acknowledgement when sending a SMS: # Pyt Python hon exa exampl mple e # http://jasminsms. http://jasminsms.com com

import   urllib2

16

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

import   urllib # Send an SMSSMS-MT MT and requ request est term terminal inal leve level l ackno acknowled wledgemen gement t call callback back to http http://my ://myserve server/ac r/acknowl knowledgem edgem params   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar', ,   'to': 'to':'+336222172' '+336222172', ,   'content': 'content':'Hello' 'Hello', , 'dlr-url':'http://myserver/acknowledgement',   'dlr-level': 'dlr-url': 'dlr-level':2} .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(params)) urlencode(params)). .read() urllib2. urllib2

And more use cases: # Pyt Python hon exa exampl mple e # http://jasminsms. http://jasminsms.com com

import   urllib2 import   urllib baseParams   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar', ,   'to': 'to':'+336222172' '+336222172', ,   'content': 'content':'Hello' 'Hello'} } # Sen Sendin ding g lon long g con conten tent t (mo (more re tha than n 160 cha chars) rs): : baseParams['content' baseParams[ 'content'] ]   =   'Very long message ................ ................................. ................................. ........................ ........ urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read() %s" # Sen Sendin ding g UCS UCS2 2 (UT (UTF-1 F-16) 6) ara arabic bic con conten tent t baseParams['content' baseParams[ 'content'] ]   =   '\x06\x23\x06\x31\x06\x46\x06\x28' baseParams['coding' baseParams[ 'coding'] ] = 8 urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read()

In PHP: <?php // Sen Sendin ding g sim simple ple mes messag sage e usi using ng PHP // http://jasminsms http://jasminsms.com .com $baseurl   =  'http://127.0.0.1:1401/send' $params   =   '?username=foo' $params.= $params .=   '&password=bar' $params.= $params .=   '&to='. '&to='.urlencode urlencode( ('+336222172' '+336222172') ) $params.=   '&content='. $params.= '&content='.urlencode urlencode( ('Hello 'Hello wor world ld !' !') ) $response   =   file_get_contents( file_get_contents($baseurl $baseurl. .$params $params); ); ?>

In Ruby: # Sen Sendin ding g sim simple ple mes messag sage e usi using ng Rub Ruby  y  # http://jasminsms. http://jasminsms.com com require   'net/http' uri   =   URI URI( ('http://127.0.0.1:1401/send' 'http://127.0.0.1:1401/send') ) params   =   {   :username   =>   'foo', 'foo',   :password   =>   'bar', 'bar', :to   =>   '+336222172', '+336222172',   :content   =>   'Hello 'Hello world world' ' } uri. uri .query   =   URI URI. .encode_www_form(params) Net:: ::HTTP HTTP. .get_response(uri) response   =   Net

3.4. HTTP API

17

 

Jasmin Documentation, Release 0.9.3-beta

jasmin.cfg / http-api The jasmin.cfg file  (INI format, located in /etc/jasmin)  contain a section called  http-api  where all ja-http API related config elements are: 1 2 3

  [http-api]   bind   port

   

=   0.0.0.0 =   1401

4 5 6 7 8

       

long_content_max_parts   =   5 # Sp Spli litt ttin ing g lo long ng co cont nten ent t ca can n be ma made de th thro roug ugh h SA SAR R op opti tion ons s or UD UDH  H  # Po Poss ssib ible le values values are: sar and ud udh h long_content_split   =   udh

         

access_log   log_level   log_file   log_format   log_date_format

9 10 11 12 13 14

 

=  /var/log/jasmin/http-access.log =   INFO =  /var/log/jasmin/http-api.log =   %(as %(asctime ctime)s )s %(lev %(levelna elname)-8 me)-8s s %(pr %(process ocess)d )d %(mes %(message sage)s )s =   %Y-%m-%d %Y-%m-%d %H:%M %H:%M:%S :%S

Table 3.5: [http-api] configuration configuration section

Element bi bind nd

Default 0. 0.0. 0.0. 0.0 0

Description Th Thee HTTP HTTP API API li list sten ener er wi will ll only only bind bind to this this spec specifi ified ed addr addres ess, s, give given n 0.0. 0.0.0. 0.0 0 the the

listener will bind on all interfaces. The binding TCP port. If th thee me mess ssag agee to be se sent nt is to be spli splitt into into seve severa rall part parts. s. This This is the the maxi maximu mum m number of individual SMS-MT messages that can be used. long_content_split ud udh h Spli Splitt ttin ing g me meth thod od:: ‘u ‘udh dh’: ’: Wil illl spli splitt usin using g 66-by byte te long long User User Data Data He Head ader er,, ‘sar ‘sar’: ’: Will split using sar_total_segments, sar_total_segments, sar_segment_seqnum, sar_segment_seqnum, and sar_msg_ref_num options. access_lo acce ss_log g /var/lo /var/log/ja g/jasmin smin/htt /httpWhere pto log all http requests (and errors). access.log log_* Python’s logging module configuration.

port 1401 long_content_max_parts 5

3.4.3 Receiv Receiving ing DLR DLR When requested through dlr-* fields when  Sending SMS-MT ,  a delivery receipt (DLR) will be sent back to the application url (set in  dlr-url) through HTTP GET/POST  depending on  dlr-method. The receiving end point must reply back using a “200 OK” status header  and a body containing an  acknowledgement acknowledgement of receiving the DLR, if one or both of these conditions are not met, the  DLRThrower service  will consider reshipment ). of the same message if   config/dlr-thrower/max_retries is not reached (see  jasmin.cfg / dlr-thrower ). In order to acknowledge DLR receipt, the receiving end point must reply back with  exactly  the following html body content: ACK/ ACK /Jasmin

Note:   It is very important to acknowledge back each received DLR, this will prevent to receive the same message many times, c.f.   Processing for details

delayed for  config/dlr-thrower/retry_delay  seconds (see  jasmin.cfg / dlrNote:   Reshipment of a message will be delayed

18

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

thrower ).

Parameters eters for a level 1 DLR HTTP Param The following parameters are sent to the receiving end point (at dlr-url) when the DLR’s dlr-level is set to 1 (SMS-C level only) Table 3.6: ja-http parameters for a level level 1 DLR

Parameter id  

Value / Pattern

Universally Universally Unique IDentifier (UUID) mesESME_* SMPP sage_status Command status level   1

Example(s)

Presence 16fd2706-8baf-433bAl82eb-8c7fada847da ways ESME_ROK, AlESME_RINVNUMDESTS ways 1 Always

Description / Notes Internal Jasmin’s Jasmin’s gateway message id used for tracking messages The delivery status This is a static value indicating the dlr-level dlr-le vel originally requested

HTTP Parameters for a level 2 or 3 DLR The following parameters are sent to the receiving end point (at dlr-url) when DLR’s dlr-level dlr-level is set to 2 or 3 (Terminal level or all levels)

3.4. HTTP API

19

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.7: ja-http parameters for a level level 2 or 3 DLR

Value /  Pattern

Exam Exampl ple( e(s) s)

Pres Pres-- Description / Notes ence

Universally Unique IDentifier (UUID) id_smsc  Integer

16fd27068baf-433b82eb8c7fada847da 2567

AlInternal Jasmin’s gateway message id used for tracking ways messages

mesESME_* sage_status SMPP Command status level   1

1

AlThis is a static value indicating the dlr-level originally ways requested Op- The time and date at which the short message was submitted tional

Parameter id

 

1311022338

Date & time format: YYMMDDhhmm Date & time

subdate

donedate sub

AlMessage id returned from the SMS-C ways ESME_ROK, AlThe delivery status ESME_RINVNUMDESTS ways

 

1311022338

format: YYMMDDhhmm Integer

 

text  

The time and date at which the short message reached it’s

tional final state 1

dlvrd   Integer

err

Op-

1

Integer

0

Text (20 char. max)

Hel Hello foo ba barr

Op- Number of short messages originally submitted. This is only tional relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if  necessary Op- Number of short messages delivered. This is only relevant tional where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary Op- Where appropriate this may hold a Network specific error tional code or an SMSC error code for the attempted delivery of the message Op Op-- The first 20 characters of the short message tional

Processing The flowchart below describes how dlr delivery and retrying policy is done inside DLRThrower service:

jasmin.cfg / dlr-thrower The  jasmin.cfg  file   (INI format, located in /etc/jasmin)   contain a section called   deliversm-thrower  where all DLRThrower service related config elements are: 1 2 3 4 5 6

  [dlr-thrower]          

http_timeout   retry_delay   max_retries   log_level   log_file  

20

=   30 =   30 = 3 =   INFO =  /var/log/jasmin/dlr-thrower.log

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

3.4. HTTP API

21

 

Jasmin Documentation, Release 0.9.3-beta

7 8

  log_format     log_date_format

 

=   %(as %(asctime ctime)s )s %(lev %(levelna elname)-8 me)-8s s %(pr %(process ocess)d )d %(mes %(message sage)s )s =   %Y-%m-%d %Y-%m-%d %H:%M %H:%M:%S :%S

Table 3.8: [http-api] configuration configuration section

Elem Elemen entt Def Defau ault lt htt http_t p_time imeout out 30 ret retry_ ry_del delay ay 30 ma max_ x_re retr trie iess log_*

3

Desc Descri rip pti tion on Set Setss socket socket timeou timeoutt in second secondss for outgoi outgoing ng client client htt http p connec connectio tions. ns. Defi Define ne how how ma many ny second secondss sho should uld pas passs within within the que queuin uing g system system for retryi retrying ng a faile failed d throw. Defin Definee ho how w ma many ny re retr trie iess shou should ld be perf perfor orme med d fo forr fail failin ing g thro throws ws of DLR. DLR. Python’s logging module configuration.

3.4.4 Receiv Receiving ing SMS-MO SMS-MO SMS-MO  incoming messages (Mobile   Originated) are forwarded by Jasmin to defined URLs using simple  HTTP GET/POST, the forwarding is made by   deliverSmHttpThrower  service, and the URL of the receiving endpoint is selected through a route checking process (c.f.  The message router). router).

Receiving endpoint is a third party application which acts on the messages received and potentially generates replies,  for more details about HTTP Client connector management). ( HTTP Client connector manager  for The parameters below are transmitted for each SMS-MO, the receiving end point must provide an url (set in   jasminApi.HttpConnector.baseurl nApi.HttpConnector.method ). ) and parse the below parameters using GET or POST method (depends on  jasmi-

The receiving end point must reply back using a “200 OK” status header  and a body containing an  acknowledgement acknowledgement of receiving the SMS-MO, if one or both of these conditions are not met, the  deliverSmHttpThrower service  will consider reshipment of the same message if   config/deliversm-thrower/max_retries  is not reached, (see  jasmin.cfg /  deliversm-thrower ). In order to acknowledge SMS-MO receipt, the receiving end point must reply back with  exactly  the following html body content: ACK/Jasmin ACK/

prevent to receive the same message Note:   It is very important to acknowledge back each received SMS-MO, this will prevent many times, c.f.   Processing for details

Note:   Reshipment of a message message will be delayed for for   config/deliversm-thrower/retry_delay seconds (see  jasmin.cfg  / deliversm-thrower ))..

HTTP Parameters When receiving an URL call from Jasmin’s  deliverSmHttpThrower service, the below parameters are delivered (at least Always present ones).

22

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.9: ja-http receiving SMS SMS parameters

Parameter id  

Value /  Pattern

Example(s)

Pres- Description / Notes ence

16fd2706-8baf433b-82eb8c7fada847da

Always

Internal Jasmin’s Jasmin’s gateway message id

Always

Originating address

Always

Destination address, only one address is supported per request

Always

Jasmin http connector id

1, 2 or 3

+21620203060, 20203060, Jasmin +21620203060, 20203060, Jasmin 23, bcd, MTN, clickatell, beepsend 2

Numeric

8

YYYY-MMDD hh:mm:ss Text

2013-07-16 00-46:54

Universally Unique IDentifier (UUID) from   Originating address

to

 

Destination address

origin- Alphanumeric connectorid priority coding validity content binary

Hello world !

Hexlified binary content

062A 062A06 0630 3062 62A A

OpDefault is 1 (lowest priority) tional OpDefault is 0, accepts values all allowed values in SMPP tional protocol [2] OpThe validity period parameter indicates the Jasmin GW tional expiration time, after which the message should be discarded if not delivered to the destination AlContent of the message ways Al Al-Content of the message in binary hexlified binary  hexlified form  form ways

receiving ng multiple parts of a long SMS SMS-MO, -MO, deliverSmHttpThr Note:   When receivi deliverSmHttpThrower ower service will concatenate the content of all the parts and then throw one http call with concatenated  content .

Processing The flowchart below describes how message delivery and retrying policy are done inside   deliverSmHttpThrower  ser  service:

jasmin.cfg / deliversm-thrower The   jasmin.cfg  file  (INI format, located in /etc/jasmin)  contain a section called   deliversm-thrower  where all deliverSmHttpThrower service related config elements are: 1 2 3 4 5 6 7 8

  [deliversm-thrower]            

http_timeout   retry_delay   max_retries   log_level   log_file   log_format  

  log_date_format

3.4. HTTP API

=   30 =   30 = 3 =   INFO =   /var/log/jasmin /var/log/jasmin/deliversm-throwe /deliversm-thrower.log r.log =   %(as %(asctime ctime)s )s %(lev %(levelna elname)-8 me)-8s s %(pr %(process ocess)d )d %(mes %(message sage)s )s  

=   %Y-%m-%d %Y-%m-%d %H:%M %H:%M:%S :%S

23

 

Jasmin Documentation, Release 0.9.3-beta

24

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.10: [http-api] configuration section section

Elem Elemen entt Def Defau ault lt htt http_t p_time imeout out 30 ret retry_ ry_del delay ay 30 max_retri max_re tries es log_*

3

Desc Descri rip pti tion on Set Setss socket socket timeou timeoutt in second secondss for outgoi outgoing ng client client htt http p connec connectio tions. ns. Defi Define ne how how ma many ny second secondss sho should uld pas passs within within the que queuin uing g system system for retryi retrying ng a faile failed d throw. Define Define how how ma many ny ret retrie riess should should be perfor performed med for faili failing ng thr throw owss of SMS-M SMS-MO. O. Python’s logging module configuration.

Checking king account account balance balance 3.4.5 Chec In order to check user account balance and quotas, user may request a  HTTP GET/POST from the following URL: http://127.0.0.1:1401/balance Note:   Host 127.0.0.1 and port 1401 are default values and configurable in /etc/jasmin/jasmin.cfg, see  jasmin.cfg / http-api.

HTTP request parameters Table 3.11: ja-http balance request parameters parameters

Param aramet eter er

Value alue / Patte attern rn username   Tex extt (30 char char. max max)) password   Tex extt (30 char char. max max))

Ex Exam ampl ple( e(s) s) jasmin jasmin_us _user er jasmin jasmin_pa _pass ss

Pr Pres esen ence ce Mandat Mandatory ory Man Mandat datory ory

Desc Descri ript ptio ion n / No Note tes s Userna Username me for Jasmi Jasmin n use userr accoun account. t. Passw Password ord for Jasmi Jasmin n use userr accoun account. t.

HTTP response Successful response: {"balance" "balance": :   100.0, 100.0,   "sms_count": "sms_count":   "ND"} "ND"}

Otherwise, an error is returned.

Examples Here is an example of how to check balance: # Pyt Python hon exa exampl mple e # http://jasminsms. http://jasminsms.com com

import   urllib2 import   urllib import   json # Che Check ck use user r bal balanc ance e params   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar'} } urllib2.urlopen( urlopen("http://127.0.0.1:1401/balance? "http://127.0.0.1:1401/balance?%s "   %   urllib. urllib.urlencode(params)) urlencode(params)). .read() response   =   urllib2. %s" response   =   json. json.loads(response)

'Balance:' , , response[ resp onse['balance' 'balance'] ]  print    'Balance:', 'SMS Count Count:' :', respo response[ nse['sms_count' 'sms_count'] ]  print

3.4. HTTP API

25

 

Jasmin Documentation, Release 0.9.3-beta

#Bala #Balance: nce: 100. 100.0 0 #SMS #SM S Cou Count: nt: ND

3.4.6 Chec Checking king rate rate price It is possible to ask Jasmin’s HTTPAPI for a message rate price before sending it, the request will lookup the route to be considered for the message and will provide the rate price if defined. Request is done through HTTP GET/POST  to the following URL: http://127.0.0.1:1401/rate Note:   Host 127.0.0.1 and port 1401 are default values and configurable in /etc/jasmin/jasmin.cfg, see  jasmin.cfg / http-api.

HTTP request parameters Table 3.12: ja-http rate request parameters parameters

Parameter to  

Value /  Pattern

Destination address from   Originating address 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 or 14 user- Text (30 char. name max) pass- Text (30 char. word max) coding

content

Text

Example(s)

Presence Description / Notes

20203050 Manda-Destination address, only one address is supported per request tory 20203050,OpOriginating address, In case rewriting of the sender’s address is Jasmin tional supported or permitted by the SMS-C used to transmit the message, this number is transmitted as the originating address 1 OpSets the Data Coding Scheme bits, default is 0, accepts values all tional allowed values in SMPP protocol  1  jasmin_user  jasmin_pass

Manda-Username for Jasmin user account. tory Manda-Password for Jasmin user account. tory

Hello world !

OpContent to be sent tional

HTTP response Successful response: {"submit_sm_count" "submit_sm_count": :   2,   "unit_rate" "unit_rate": :   2.8 2.8} }

Where submit_sm_count submit_sm_count is the number of message units if the content is longer than 160 characters,  content parameter is optional for requesting rate price. Otherwise, an error is returned. Otherwise, an error is returned: Error Err or "No route route found" found"

26

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Examples Here is an example of how to check rate price: Python hon exa exampl mple e # Pyt # http://jasminsms. http://jasminsms.com com

import   urllib2 import   urllib import   json # Che Check ck mes messag sage e rat rate e pri price ce params   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar', ,   'to': 'to':   '06222172'} '06222172'} response   =   urllib2. urllib2.urlopen( urlopen("http://127.0.0.1:1401/rate? "http://127.0.0.1:1401/rate?%s %s" "   %   urllib. urllib.urlencode(params)) urlencode(params)). .read() json.loads(response) response   =   json.

 print   'Unit 'Unit rat rate e pri price: ce:' ', resp response[ onse['unit_rate' 'unit_rate'] ]  print   'Units:', 'Units:', response[ response['submit_sm_count' 'submit_sm_count'] ] #Unit it rat rate e pri price: ce: 2.8 #Un #Units #Un its: : 1

Table 3.13: Data coding schemes schemes

Bitmask

Value   Meaning

 

00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001101 00001110

                         

0 1 2 3 4 5 6 7 8 9 10 13 14

                         

SMSC Default Alphabet IA5 (CCITT T.50)/ASCII (ANSI X3.4) Octet unspecified (8-bit binary) Latin 1 (ISO-8859-1) Octet unspecified (8-bit binary) JIS (X 0208-1990) Cyrllic (ISO-8859-5) Latin/Hebre Latin/Hebrew w (ISO-8859-8) UCS2 (ISO/IEC-10646) Pictogram Encoding ISO-2022-JP (Music Codes) Extended Kanji JIS(X 0212-1990) KS C 5601

3.5 SMP SMPP P Server Server API This document is targeted at software designers/programmers wishing to integrate SMS messaging through a stateful tcp protocol  SMPP v3.4, if you feel this does not fit your needs and that you are more “web-service-guy” then you still can try HTTP try HTTP API API.. SMS Messages can be transmitted using SMPP protocol, the following requirements must be met to enable the service : • You need a Jasmin use userr account • You need sufficient cred credit it on your Jasmin user account 1 Note:   The ABCs:

•   MT is referred to Mobile Terminated, a SMS-MT is an SMS sent to mobile 1

Billing

3.5. SMPP Server API

27

 

Jasmin Documentation, Release 0.9.3-beta

•   MO is referred to Mobile Originated, a SMS-MO is an SMS sent from mobile

3.5.1 Featur Features es The SMPP Server API allows you to send and receive SMS and delivery receipts (DLR) through Jasmin’s connectors, send and receive long (more than 160 characters) SMS and unicode/binary content.

jasmin.cfg / smpp-server The jasmin.cfg file  (INI format, located in /etc/jasmin)  contain a section called  smpp-server where all SMPP Server API related config elements are: 1 2 3 4

  [smpp-server]   id   bind   port

     

=   "smpps_01" =   0.0.0.0 =   2775

5 6 7 8 9 10

       

sessionInitTimerSecs   =   30 enquireLinkTimerSecs   =   30 inactivityTimerSecs   =   300 responseTimerSecs   =   60

  pduReadTimerSecs

 

=   30

11 12 13 14 15

       

log_level   log_file   log_format   log_date_format

 

=   INFO =   /var/log/jasmin /var/log/jasmin/default-smpps_01 /default-smpps_01.log .log =   %(as %(asctime ctime)s )s %(lev %(levelna elname)-8 me)-8s s %(pr %(process ocess)d )d %(mes %(message sage)s )s =   %Y-%m-%d %Y-%m-%d %H:%M %H:%M:%S :%S

Table 3.14: [smpp-server] configuration configuration section

Element id bind bind port sessionInitTimerSecs enquireLinkTimerSecs inactivityTimerSecs responseTimerSecs pduReadTimerSecs log_*

DeDescription fault sm smpp pps_ s_01 01Th Thee SM SMPP PP Serv Server er id id,, used used to id iden enti tify fy the the inst instan ance ce in case case yo you u use use mu mult ltip iple le serv server erss per Jasmin process. 0. 0.0. 0.0. 0.0 0 The The SM SMPP PP Serv Server er API API li list sten ener er will will on only ly bind bind to this this spec specifi ified ed addr addres ess, s, give given n 0.0. 0.0.0. 0.0 0 the listener will bind on all interfaces. 2775 30

The binding TCP port. Protoc Protocol ol tuning tuning par parame ameter ter:: tim timeou eoutt for a bin bind d reques request. t.

30

Protoc Protocol ol tuning tuning par parame ameter ter:: tim timeou eoutt for an enquir enquire_l e_link ink reques request. t.

300

Protoc Protocol ol tuning tuning par parame ameter ter:: ina inacti ctivit vity y timeou timeout. t.

60

Protoc Protocol ol tuning tuning par parame ameter ter:: glo global bal req reques uestt timeou timeout. t.

30

Protoc Protocol ol tuning tuning par parame ameter ter:: bin binary ary pdu rea ready dy timeo timeout. ut. Python’s logging module configuration.

Binding to SMPP Server Binding Using a proper SMPP Client application (or a Jasmin SMPP Client), the following parameters must be considered:

28

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.15: SMPP Server binding parameters parameters

Param aramet eter er

Value alue / Patte attern rn system_id   Tex extt (30 char char. max max)) password   Tex extt (30 char char. max max))

Ex Exam ampl ple( e(s) s) jasmin jasmin_us _user er jasmin jasmin_pa _pass ss

Pr Pres esen ence ce Mandat Mandatory ory Man Mandat datory ory

Desc Descri ript ptio ion n / No Note tes s Userna Username me for Jasmi Jasmin n use userr accoun account. t. Passw Password ord for Jasmi Jasmin n use userr accoun account. t.

Supported SMPP PDUs Jamsin’s SMPP Server is supporting the following PDUs: • bind_transmi bind_transmitter tter • bind_transcei bind_transceiver ver • bind_recei bind_receiver ver • unb unbind ind • subm submit_s it_sm m • delive deliver_sm r_sm • enqu enquire_l ire_link  ink 

3.6 The message message rou router ter The message router is Jasmin’s decision making component for routing every type of exchanged message through the gateway: 1. MO Messages Messages (deliver_sm) (deliver_sm) 2. MT Messages Messages (submit_sm) (submit_sm) The router is provisioned through: • Perspecti Perspective ve broker interf interface ace (python programmatic programmatic API)  and  MT router manager  • jCli modules: modules: MO router manager  and Each time a message is requiring a route decision the following process is executed:

3.6.1 Proc Process ess flow flow There’s one  MORoutingTable  and one  MTRoutingTable  objects holding respective routes for each direction (MT or MO), these are  Route  objects that hold one or many  Filter  (s) objects and one destination  Connector  (or many connectors in some specific cases, c.f.  Multiple connectors). As explained by the above routing process flow figure, for each message and depending on its direction, a routing table is loaded and an iterative testing is run in order to select a final destination connector or to reject (returning no connector) it, routes are selected in descendant order, and their respective filter objects are tested against the  Routable object (It is an extension of the low-level SMPP PDU object representing a message, more information in  Routable).

Examples MO Routing

Having the below MO routing table set through a jCli console session:

3.6. The message router

29

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.2: Routi Routing ng process process flo flow w

30

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jcli jcli : moro morout uter er -l #MO Route order Type #30 StaticMORoute #20 RandomRoundrobinMORoute #0 DefaultRoute Tota Total l MO Rout Routes es: : 3

Connector ID(s) http_3 http_1, http_2 http_def

Filter(s) <DestinationAddrFilter (d <DateIntervalFilter (2015

The following routing cases are considered: • MO message is routed to http_3 if : –   Its destination address matches the regular expression “^+33d+”

• MO message is routed to http_1 OR  http_2 if : –  Its received in summer months (June, July and August) of year 2015 and in working hours interval (8pm to 6am)

• MO message is routed to http_def   if  if : –  None of the above routes are matched (fallback / default route) MT Routing

Having the below MT routing table set through a jCli console session: jcli jcli : mtro mtrout uter er -l #MT Route order Type #100 RandomRoundrobinMTRoute #91 StaticMTRoute #90 StaticMTRoute Tota Total l MT Rout Routes es: : 3

Rate 0.00 0.00 0.00

C Co onnector ID(s) smpp_1, smpp_2 smpp_4 smpp_3

Filter(s) <DestinationAddrF <GroupFilter (gid <GroupFilter (gid

The following routing cases are considered: • MT message is routed to smpp_1 OR  smpp_2 if : –   Its destination address matches the regular expression “^+33d+”

• MT message is routed to smpp_4 if : –  Its sent by a user in group G2 and in working hours interval (8pm to 6am)

• MT message is routed to smpp_3 if : –  Its sent by a user in group G2 Note:   The route order is very importan important: t: if we swap last both routes (#90 and #91) we will run into a shadowing route where all MT messages sent by a user in group G2 will be routed to smpp_3, no matter what time of the day it is.

there’s no DefaultRoute, this will lead to message rejection rejection if none of the configured routes Note:   In this example, there’s are matched.

Note:   Route’s  rate  are discussed in Billing in  Billing..

3.6. The message router

31

 

Jasmin Documentation, Release 0.9.3-beta

components ents 3.6.2 Router compon The router components are mainly python objects having the unique responsibility of routing messages to Jasmin connectors.

Routable The Routable class is extended by child classes to hold necessary information about the message to be  routed .

Fig. 3.3: jjasmin.routing.Rout asmin.routing.Routables.* ables.* The   SimpleRoutablePDU SimpleRoutablePDU  is only used for Jasmin unit testing,  RoutableSubmitSm   and   RoutableDeliverSm   are used depending on the message direction: • MO:   RoutableDeliverSm • MT MT::   RoutableSubmi RoutableSubmitSm tSm All routables provide a tagging api through the  addTag(),  hasTag(),  getTags(),  removeTag(),  flushTags()  methods, this feature is mainly used in the interceptor the  interceptor,,  there’s a concrete example of such usage  here. Table 3.16:   RoutableSubmitSm RoutableSubmitSm attributes

Attribute PDU user date_time

Type jas jasmin min.ve .vendo ndorr.sm .smpp. pp.pdu pdu.pd .pdu_t u_type ypes.P s.PDUR DURequ equest est jasmin.routing.jasminApi.User datetime.datetime

Description The SMP SMPP P submi submit_s t_sm m PDU Jasmin user sending the message Date & time of message send request

Table 3.17:   RoutableDeliverSm RoutableDeliverSm attributes

Attribute

Type

Description

PDU conn connec ecto torr date_time

jas jasmin min.ve .vendo ndor r.sm .smpp. pp.pdu pdu.pd .pdu_t u_type ypes.P s.PDUR equest est jasm jasmin in.r .rou outi ting ng.j .jas asmi minA nApi pi.C .Con onne nect ctor or DURequ datetime.datetime

The SMP SMPP P del deliv iver_ er_sm sm Jasm Jasmin in or orig igin in conn co nnec ecto torPDU r of the the mess messag agee Date & time of message reception

32

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Connector The Connector class is extended by child classes to represent concrete HTTP or SMPP Client connectors.

Fig. 3.4: jasmin.routing.jas jasmin.routing.jasminApi.Connector minApi.Connector and childs

Filter The Filter class is extended by child classes to define specific filters which are run by Jasmin router to match a desired Routable, every filter have a public   match(rout match(routable) able) method returning a boolean value ( True  if the filter matches the given Routable). As explained, filters provide an advanced and customizable method to match for routables and decide which route to consider, the figure below shows the  Filter implementations provided by Jasmin, you can extend the  Filter  class and build a new filter of your own. The  usedFor   attribute indicates the filter-route compatibility, as some filters are not suitable for both MO and MT routes like the examples below: •   UserFilter and  GroupFilter: MO Messages are not identified by a user or a group, they are received through a connector •  ConnectorFilter: MT Messages are not coming from a connector, they are sent by a known user/group.

Route A  Route  class holds one or many filters, the   matchFilters(routable) matchFilters(routable)  method is called to match the given routable against every filter of the  Route (using AND  operation when there’s many filters), if the matching succeed, the Jamsin router will ask for the  Connector to consider by calling  getConnector()  method which will return back the  Route ‘s connector. Static and default routes are the simplest implemented routes, the difference between them is:

3.6. The message router

33

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.5: jjasmin.routing.Fil asmin.routing.Filters.* ters.*

Fig. 3.6: jjasmin.routing.Rout asmin.routing.Routes.* es.*

34

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

•   DefaultRoute   ‘s  matchFilter()  method will always return True, it is usually a fallback route matching any Routable •   StaticMORoute   and  StaticMTRoute   will return one  Connector  after matching the filters with  matchFilters(routable)  method There’s a lot of things you can do by extending the  Route class, here’s a bunch of possibilities: •   Failover route: Will always return the same connector when it is up, and will fail over/back between master and backup connectors depending on their status •  Best quality routing: Implement a connector scoring system to always return the best quality route for a given message Multiple connectors

When extending  Route   class, it is possible to customize the behavior of the route and that’s what  RoundrobinMORoute   and   RoundrobinMTRoute RoundrobinMTRoute  do, they are initially provisioned with a set of connectors, and the  getConnector()  method is overloaded to return a random connector from it; this can be a basic usage of a load balancer route.

RoutingTable The  RoutingTable   class is extended by destination-specific child classes (MO or MT), each class provide a  Route provisioning api: provisioning •  add(route, order): Will add a new route at a given order, will replace an older route having the same order •   remove(order): Will remove the route at the given order •   getAll(): Will return all the provisioned routes •   flush(): Will remove all provisioned routes The   getRouteFor(routable)  will get the right route to consider for a given routable, this method will iterate through all the provisioned routes in descendant order to call their respective   matchFilters matchFilters(routable) (routable) method.

Interceptio ception n 3.7 Inter Starting from 0.7.0, Jasmin provides a convenient way for users to hook third party logics on  intercepted   messages (submit_sm or deliver_sm) before proceding to The to  The message router. router. Interception of message is based on filter matching, just like the router; every intercepted message will be handed to a user-script user-scri pt written in Python in Python.. This feature permits users to implement custom behaviors on top of Jasmin router, here’s some possible scenarios: • Billing & charging of MO messages, • Implement HLR lo lookup okup for a better SMS MT rrouting, outing, • Change a pdu content: fix npi/ton, prefixi prefixing/suffixing ng/suffixing n numbers, umbers, etc ... • Modify Jasmin Jasmin’s ’s res response ponse for the message message:: send back a   ESME_RINVDST ESME_RINVDSTADR ADR  instead of   ESME_ROK  for   for example. • etc ..

3.7. Interception

35

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.7: jasmin.rout jasmin.routing.RoutingT ing.RoutingTables.* ables.*

Enabling ing interceptor interceptor 3.7.1 Enabl Jasmin’s interceptor is a system service that run separately from Jasmin, it can be hosted on remote server as well; interceptord  is a system service just like  jasmind, so simply start it by typing: sudo syste systemctl mctl star start t inte intercept rceptord ord

Note:   After starting starting the  interceptord  service, you may check   /var/log/jasmin/interceptor.log  to ensure everything is okay.

Then you need to enable communication between  jasmind  and   interceptord  services by editing  jasmind  start script (locate the  jasmind.serv jasmind.service ice file in  /etc/systemd ) and replacing the following line: ExecStart= ExecS tart=/usr /usr/bin/ /bin/jasmi jasmind.p nd.py y --use --usernam rname e jcli jcliadmin admin --pas --password sword jclip jclipwd wd

by: ExecStart=/usr/bin/jasmind.py ExecStart=/usr/b in/jasmind.py --username jcliadmin --password jclipwd --enable-interceptor-client

The last step is to restart jasmind and check   /var/log/jasmin/interceptor.log to ensure connection has been successfully established by finding the following line: IN INFO FO

XX XXXX XX Au Auth then enti tica cate ted d Av Avat atar ar: : ia iadm dmin in

Intercepting cepting a message message 3.7.2 Inter As stated earlier, interceptor is behaving similarly to  The message router, router,   here’s an example of setting up a MO message (deliver_sm) (deliver_sm) interception rule through jcli through jcli management console: console:

36

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jcli : moi jcli mointe nterce rcepto ptor r -a Adding Add ing a new MO Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Defa DefaultIn ultInterce terceptor ptor <class 'jasmin.routing 'jasmin.routing.Interceptors.Def .Interceptors.DefaultInterceptor'> aultInterceptor'> arguments: script > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mo-interc ception/mo-interceptor.py) eptor.py) > ok Successful Succe ssfully ly added MOInterce MOInterceptor ptor [Defa [DefaultI ultInterc nterceptor eptor] ] with order order:0 :0

Same thing apply to setting up a MT message (submit_sm) interception rule, here’s another example using a filtered rule instead of a default one: jcli : mti jcli mtinte nterce rcepto ptor r -a Adding Add ing a new MT Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Stat StaticMTI icMTInterc ntercepto eptor r <class 'jasmin.routing 'jasmin.routing.Interceptors.Def .Interceptors.DefaultInterceptor'> aultInterceptor'> arguments: filters, filte rs, script script > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mt-interc ception/mt-interceptor.py) eptor.py) > filte filters rs U-foo;DAU-foo;DA-33 33 > orde order r 100 100 > ok Successful Succe ssfully ly added MTInterce MTInterceptor ptor [Stat [StaticMT icMTInter Intercepto ceptor] r] with orde order:100 r:100

As show in the above examples, the interception rules are straightforward, any matched message will be handed to the python2(<path_to_pyfile>) instruction. script you set through the  script python2(<path_to_pyfile>) When your python script is called it will get the following global variables set:

•   routable: one of the   jasmin.r jasmin.routing.Routabl outing.Routables.Routable es.Routable inheriters ( Routable for more details) •   smpp_status: (default to  0 ) it is the smpp response that Jasmin must return for the message, more details in Controlling response

•   http_status: (de (defa fault ult to   0) it is the http response that Jasmin must return for the message, more details in Controlling response

The script can: • Over Override ride routable parameters like setting destination or source addresses, short message, etc ... • Tag the the routable to help the router matching a desired rule (useful for HRL lookup routing) • Control Jasm Jasmin in response by setting smpp_status and/or  http_status. Some practical examples are given  below.

3.7.3 Contr Controlling olling response response The interceptor script can reject message before it goes to the router, this can be useful for implementing third party controls like: • Billing and chargin charging g authorization: reject message if user has no credits, • Reject some illegal message conte content, nt, • Enable anti-spam to prote protect ct destination users from get getting ting flooded, • etc ... In order to reject a message, message, depe depending nding on the source of message message (httpapi (httpapi ? smpp serv server er ? smpp clie client nt ?) the scrip scriptt must set  smpp_status  and/or  http_status accordingly to the error to be returned back, here’s an error mapping table for smpp:

3.7. Interception

37

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.18:  smpp_status Error mapping

Value 0 1 2 3 4 5 6 7 8 26 265 5 10 11 12 13 14 15 27 272 2 17 27 274 4

SMPP Status ESME_ROK ESME_RINVMSGLEN ESME_RINVCMDLEN ESME_RINVCMDID ESME_RINVBNDSTS ESME_RALYBND ESME_RINVPRTFLG ESME_RINVREGDLVFLG ESME_RSYSERR ES ESME ME_R _RIN INVB VBCA CAST STAR AREA EAFM FMT T ESME_RINVSRCADR ESME_RINVDSTADR ESME_RINVMSGID ESME_RBINDFAIL ESME_RINVPASWD ESME_RINVSYSID ES ESM ME_ E_RI RINV NVBC BCAS AST_ T_RE REP P ESME_RCANCELFAIL ES ESME ME_R _RIN INVB VBCA CAST STCH CHAN ANIN IND D

Description No error Message Length is invalid Command Length is invalid Invalid Command ID Invalid BIND Status for given command ESME Already in Bound State Invalid Priority Flag Invalid Registered Delivery Flag System Error Br Broa oadc dcas astt Ar Area ea Form Format at is inva invali lid d Invalid Source Address Invalid Dest Addr Message ID is invalid Bind Failed Invalid Password Invalid System ID Nu Num mbe berr of Re Repe peaated ted Br Bro oad adccasts asts is inv invalid alid Cancel SM Failed Br Broa oadc dcas astt Ch Chan anne nell In Indi dica cato torr is inva invali lid d

19 20 21 19 196 6 260 261 262 26 263 3 25 257 7 273 273 264 27 270 0 51 52

ESME_RREPLACEFAIL ESME_RMSGQFUL ESME_RINVSERTYP ES ESME ME_R _RIN INV VOP OPTP TPAR ARAM AMV VAL ESME_RINVDCS ESME_R ESME_RINV INVSRC SRCADD ADDRSU RSUBUN BUNIT IT ESME_R ESME_RINV INVDST DSTADD ADDRSU RSUBUN BUNIT IT ES ESME ME_R _RIN INVB VBCA CAST STFR FREQ EQIN INT T ES ESM ME_ E_RP RPR ROH OHIB IBIITE TED D ESME ESME_R _RIN INVB VBCA CAST STSR SRV VGR GRP P ESME_R ESME_RINV INVBCA BCAST STALI ALIAS_ AS_NA NAME ME ES ESME ME_R _RBC BCAS ASTQ TQUE UER RYF YFAI AIL L ESME_RINVNUMDESTS ESME_RINVDLNAME

Replace SM Failed Message Queue Full Invalid Service Type In Inv val alid id Opti Option onal al Para Parame mete terr Value alue Invalid Data Coding Scheme Sou Source rce Add Addres resss Sub unit unit is In Inva vali lid d Des Destin tinati ation on Add Addres resss Sub unit unit is In Inva valid lid Br Broa oadc dcas astt Freq Freque uenc ncy y Inte Interv rval al is inva invali lid d ESM ESME Pro Prohi hib bited ited fro rom m us usin ing g spe specifie cified d oper peratio ation n Broa Broadc dcas astt Serv Servic icee Gr Grou oup p is inv invalid alid Bro Broadc adcast ast Ali Alias as Name Name is inva invalid lid qu quer ery_ y_br broa oadc dcas ast_ t_sm sm op oper erat atio ion n fail failed ed Invalid number of destinations Invalid Distribution List Name

26 267 7 266 19 192 2 64 19 193 3 66 67 68 69 256 256 72 73 258 258 269

ES ESME ME_R _RIN INVB VBCA CAST STCN CNTT TTYP YPE E ESME_R ESME_RINV INVNUM NUMBCA BCAST_ ST_ARE AREAS AS ES ESME ME_R _RIN INV VOP OPTP TPAR ARST STRE REAM AM ES ESM ME_ E_RI RINV NVDE DEST STF FLA LAG G ES ESME ME_R _ROP OPTP TPAR ARNO NOT TALL ALLWD ESME ESME_R _RIN INVS VSUB UBRE REP P ESME_RINVESMCLASS ESME_RCNTSUBDL ESME_RSUBMITFAIL ESME ESME_R _RSE SER RTYPU TYPUN NAUT UTH H ESME_RINVSRCTON ESME_RINVSRCNPI ESME ESME_R _RSE SER RTYPU TYPUN NAVAI AIL L ESME_RBCASTFAIL

Br Broa oadc dcas astt Co Cont nten entt Typ ypee is inva invali lid d Number Number of Broadc Broadcast ast Are Areas as is inva invalid lid Er Erro rorr in th thee op opti tion onal al pa part rt of the the PD PDU U Bo Body dy De Dessti tina nattion flag flag is invali alid (subm submiit_m t_multi) lti) Opti Option onal al Para Parame mete terr no nott al allo lowe wed d In Inv val alid id subm submit it wi with th repl replac acee requ reques estt (i.e (i.e.. subm submit it_s _sm m wi with th repl replac ace_ e_if if_p _pre rese sent nt_fl _flag ag se Invalid esm_class field data Cannot Submit to Distribution List submit_sm or submit_multi failed ES ESME ME No Nott auth author oris ised ed to use use spec specifi ified ed serv servic ice_ e_ty type pe Invalid Source address TON Invalid Source address NPI Sp Spec ecifi ified ed se serv rvic ice_ e_ty type pe is una unavaila ailabl blee broadcast_sm operation failed

80

ESME_RINVDSTTON

Invalid Destination address TON

38

Continued on next pag

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Value 81 83 84 85 88 27 271 1 97 98 99 100 101 102 103 25 259 9 194 26 268 8 255 25 254 4 19 195 5

Table 3.18 – continued from pre previous vious page SMPP Status Description ESME_RINVDSTNPI Invalid Destination address NPI ESME_RINVSYSTYP Invalid system_type field ESME_RINVREPFLAG Invalid replace_if_present flag ESME_RINVNUMMSGS Invalid number of messages ES ESM ME_ E_R RTHR THROTT TTLE LED D Th Thrrot ottl tlin ing g er erro rorr (ESM (ESME E ha hass excee ceede ded d allo llowed wed messag ssagee limi imits ES ESME ME_R _RBC BCAS ASTC TCAN ANCE CELF LFAI AIL L ca canc ncel el_b _bro road adca cast st_s _sm m op oper erat atio ion n fail failed ed ESME_RINVSCHED Invalid Scheduled Delivery Time ESME_RINVEXPIRY Invalid message validity period (Expiry time) ESME_RINVDFTMSGID Predefined Message Invalid or Not Found ESME_RX_T_APPN ESME Receiver Temporary App Error Code ESME_RX_P_APPN ESME Receiver Permanent App Error Code ESME_RX_R_APPN ESME Receiver Reject Message Error Code ESME_RQUERYFAIL query_sm request failed ES ESM ME_ E_RS RSER ERTY TYPD PDE ENI NIED ED Spe Speci cifie fied d ser erv vice_ ice_ttyp ypee is deni enied ESME_RINVPARLEN Invalid Parameter Length ES ESME ME_R _RIN INVB VBCA CAST STMS MSGC GCLA LASS SS Br Broa oadc dcas astt Mess Messag agee Cl Clas asss is inva invali lid d ESME_RUNKNOWNERR Unknown Error ES ESME ME_R _RDE DELI LIVE VER RYFAI YFAILU LURE RE Deli Delive very ry Fa Fail ilur uree (u (use sed d fo forr data data_s _sm_ m_re resp sp)) ES ESME ME_R _RMI MISS SSIN INGO GOPT PTP PAR ARAM AM Ex Expe pect cted ed Opti Option onal al Pa Para rame mete terr mi miss ssin ing g

As for http errors, the value you set in  http_status will be the http error code to return. Note:   When setting  http_status  to some value different from 0, the  smpp_status  value will be automatically set to 255  (ESME_RUNKNOWNERR). (ESME_RUNKNOWNERR).

Note:   When setting  smpp_status  to some value different from 0, the  http_status  value will be automatically set to 520 (Unknown error).

Checkout the MO Charging  example to see how’s rejection is done.

3.7.4 Scripti Scripting ng examples examples You’ll find below some helping examples of scripts used to intercept MO and/or MT messages.

HLR Lookup routing The following script will help the router decide where to send the MT message, let’s say we have some HLR lookup webservice to call in order to know to which network the destination number belong, and then tag the routable for later filtering in router: "T "Thi his s sc scri ript pt wi will ll ca call ll HL HLR R lo look okup up ap api i to ge get t th the e MC MCC/ C/MN MNC C of th the e de dest stin inat atio ion n nu numb mber er" "

import   requests,   json hlr_lookup_url   =   "https://api.som "https://api.some-provider.com/hl e-provider.com/hlr/lookup" r/lookup" data   =   json. json.dumps({ dumps({'number' 'number': : rout routable able. .pdu pdu. .params[ params['destination_addr' 'destination_addr']}) ]}) r   =   requests. requests.post( post(hlr_ hlr_looku lookup_ur p_url, l, data, auth auth= =('user' 'user', ,   '*****'))

3.7. Interception

39

 

Jasmin Documentation, Release 0.9.3-beta

if   r.json[ json['mnc' 'mnc'] ]   ==   '214': '214': # Spain Spain if   r.json[ json['mcc' 'mcc'] ]   ==   '01': '01': # Voda Vodaphone phone routable. routable .addTag( addTag(21401 21401) ) elif   r.json[ json['mcc' 'mcc'] ]   ==   '03': '03': # Ora Orange nge routable. routable .addTag( addTag(21403 21403) ) json['mcc' 'mcc'] ]   ==   '25': '25': elif   r.json[ # Lyc Lyca a mob mobile ile routable. routable .addTag( addTag(21425 21425) )

The script is tagging the routable if destination is Vodaphone, Orange or Lyca mobile; that’s because we need to route message to different connector based on destination network, let’s say: •   Vodaphone  needs to be routed through  connectorA •   Orange  needs to be routed through  connectorB •  Lyca mobile  needs to be routed through  connectorC • All the res restt needs to be routed through connectorD Here’s the routing table to execute the above example: jcli jcli : mtro mtrout uter er -l #Order Type #1 #102 02 St Stat atic icMT MTRo Rout ute e #1 #101 01 St Stat atic icMT MTRo Rout ute e #1 #100 00 St Stat atic icMT MTRo Rout ute e #0 DefaultRoute Tota Total l MT Rout Routes es: : 4

Rate 0 (! (!) ) 0 (! (!) ) 0 (! (!) ) 0 (!)

Connector ID(s) sm smpp ppc( c(co conn nnec ecto torA rA) ) sm smpp ppc( c(co conn nnec ecto torB rB) ) sm smpp ppc( c(co conn nnec ecto torC rC) ) smppc(connectorD)

Filter(s) <T <TG G (t (tag ag=2 =214 1401 01)> )> <T <TG G (t (tag ag=2 =214 1403 03)> )> <T <TG G (t (tag ag=2 =214 1425 25)> )>

MO Charging In this case, the script is calling CGRateS calling  CGRateS charging  charging system to check if user has sufficient balance to send sms, based on the following script, Jasmin will return a  ESME_ROK if user balance, or  ES  ESME_RDELIVERYF ME_RDELIVERYFAILURE AILURE if not: """This script t will recei receive ve Mobil Mobile-Ori e-Origina ginated ted mess messages ages and  """This scrip ask CGRa CGRateS teS for autho authoriza rization tion throu through gh Apie ApierV2.G rV2.GetMax etMaxUsag Usage e call call. . """ import   json,   socket

from    datetime   import   datetime from  CGR_HOST="172.20.20.140" CGR_HOST= CGR_PORT= CGR_PORT =3422

def   call(sck, call(sck, name, params): params): # Bui Build ld the request request request   =   dict( dict(id id= =1, params= params =list list(params), (params), =name) method= method sck. sck .sendall(json sendall(json. .dumps(request) dumps(request). .encode()) # Th This is mu must st lo loop op if re resp sp is bi bigg gger er th than an 4K  buffer   =   '' data   =   True   data: while   =   sck. sck.recv( recv(4096 4096) ) data buffer   +=   data

40

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

if   len len(data) (data)   <   4096: 4096:  break response   =   json. json.loads( loads(buffer buffer. .decode()) if   response. response.get( get('id' 'id') )   !=   request. request.get( get('id' 'id'): ): raise   Exception( Exception("exp "expected ected id= id=%s %s, , rec receiv eived ed id= id=%s %s: :   %s %s" " %(request (request. .get( get('id' 'id'), ), respo response nse. .get( get('id' 'id'), ), response. response .get( get('error' 'error'))) ))) response.get( get('error' 'error') )   is no None: if   response. not t   None: raise   Exception(response Exception(response. .get( get('error' 'error')) ))

return   response. response.get( get('result' 'result') ) sck   =   None globals()[ globals ()['sck' 'sck'] ]   =   sck globals()[ ()['json' 'json'] ]   =   json globals try: socket.create_connectio create_connection((CGR_HOST, n((CGR_HOST, CGR_PORT)) sck   =   socket. Prep epar are e fo for r RP RPC C ca call ll # Pr name   =   "ApierV2.GetMaxUsage" params   =   [{ "Category" "Category": :   "sms-mt" "sms-mt", , "Usage" "Usage": :   "1" "1", , "Direction": :   "*outbound" outbound", , "Direction" "ReqType" "ReqType": :   "*subscribers" subscribers", , "TOR": :   "*sms-mt" sms-mt", , "TOR" "ExtraFields" "ExtraFields": : {"Cli": "Cli": rou routab table le. .pdu pdu. .params[ params['source_addr' 'source_addr']}, ]}, "Destination" "Destination": : routa routable ble. .pdu pdu. .params[ params['destination_addr' 'destination_addr'], ], "Account" "Account": :   "*subscribers" subscribers", , "Tenant" "Tenant": :   "*subscribers" subscribers", , "SetupTime": : datetime datetime. .utcnow() utcnow(). .isoformat()   +   'Z' 'Z'}] }] "SetupTime" result   =   call(sck, call(sck, name, para params) ms)

except   Exception, Exception, e: got t an er erro ror r wh when en ca call llin ing g fo for r ch char argi ging  ng  # We go # Retur Return n ESME_ ESME_RDEL RDELIVERY IVERYFAIL FAILURE  URE  smpp_status   =   254 else: # CG CGRa Rate teS S ha has s re retu turn rned ed a va valu lue e

if   type(result) type(result)   ==   int   and   result   >=   1: # Ret Return urn ESM ESME_R E_ROK  OK  smpp_status   =   0 else: # Retu Return rn ESME_ ESME_RDELI RDELIVERY VERYFAILU FAILURE  RE  smpp_status   =   254 finally: if   sck   is no not t   None: None: sck. sck .close()

Overriding source address There’s some cases where you need to override sender-id due to some MNO policies, in the following example all intercepted messages will have their sender-id set to 123456789:

3.7. Interception

41

 

Jasmin Documentation, Release 0.9.3-beta

"This script will over override ride send sender-id er-id" " routable. routable .pdu pdu. .params[ params['source_addr' 'source_addr'] ]   =   '123456789'

Activate logging The following is an example of activating log inside a script: "This "Th is is how log loggin ging g is don done e ins inside ide int interc ercept eption ion scr script ipt" "

import   logging # Se Set t lo logg gger  er  logger   =   logging. logging.getLogger( getLogger('logging-example' 'logging-example') ) if   len len(logger (logger. .handlers)   !=   1: hdlr   =   logging. logging.FileHandler( FileHandler('/var/log/jasmin/some_file.log' '/var/log/jasmin/some_file.log') ) logging.Formatter( Formatter(' '%(as %(asctime ctime)s )s %(lev %(levelna elname)s me)s %(mes %(message sage)s )s' ') formatter   =   logging. hdlr. hdlr .setFormatter(formatter) .addHandler(hdlr) logger. logger logger. logger .setLevel(logging setLevel(logging. .DEBUG) info('Go 'Got t pdu pdu: :   %s %s' '   %   routable. routable.pdu) logger.info( logger.

3.8 Pro Programm gramming ing examples examples Subsequent chapters present how to send and receive messages through Jasmin HTTP Jasmin  HTTP API API and  and some more advanced use cases, such as manipulating receipts and complex routings, will look like.  The message router chapters router  chapters It is assumed the reader has already installed Jasmin and at least read the HTTP the HTTP API and API  and The and knows enough about Jasmin’s Jasmin’s architecture/design concepts.

3.8.1 Sendin Sending g SMS SMS Sending a SMS is done through the HTTP the  HTTP API: API: # Pyt Python hon exa exampl mple e # http://jasminsms. http://jasminsms.com com

import   urllib2 import   urllib baseParams   =   {'username': 'username':'foo' 'foo', ,   'password': 'password':'bar' 'bar', ,   'to': 'to':'+336222172' '+336222172', ,   'content': 'content':'Hello' 'Hello'} } # Sen Send d an SMS SMS-MT -MT wit with h min minima imal l par parame ameter ters s urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read() Send d an SMS SMS-MT -MT wit with h def define ined d ori origin ginati ating ng add addres ress s # Sen baseParams['from' baseParams[ 'from'] ]   =   'Jasmin 'Jasmin GW' urllib2. urllib2 .urlopen( urlopen("http://127.0.0.1:1401/send? "http://127.0.0.1:1401/send?%s %s" "   %   urllib. urllib.urlencode(baseParams)) urlencode(baseParams)). .read()

In PHP: <?php // Sen Sendin ding g sim simple ple mes messag sage e usi using ng PHP // http://jasminsms http://jasminsms.com .com

42

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

$baseurl   =  'http://127.0.0.1:1401/send' $params   =   '?username=foo' $params.= $params .=   '&password=bar' $params.= $params .=   '&to='. '&to='.urlencode urlencode( ('+336222172' '+336222172') ) $params.=   '&content='. $params.= '&content='.urlencode urlencode( ('Hello 'Hello wor world ld !' !') ) $response   =   file_get_contents( file_get_contents($baseurl $baseurl. .$params $params); ); ?>

In Ruby: # Sen Sendin ding g sim simple ple mes messag sage e usi using ng Rub Ruby  y  # http://jasminsms. http://jasminsms.com com require   'net/http' uri   =   URI URI( ('http://127.0.0.1:1401/send' 'http://127.0.0.1:1401/send') ) 'foo',   :password   =>   'bar', 'bar', params   =   {   :username   =>   'foo', :to   =>   '+336222172', '+336222172',   :content   =>   'Hello 'Hello world world' ' } uri. uri .query   =   URI URI. .encode_www_form(params) Net:: ::HTTP HTTP. .get_response(uri) response   =   Net

c.f. c.f. HTTP API  for more details about sending SMS with receipt enquiry, long content etc ...  HTTP API for

Receiving ing SMS SMS 3.8.2 Receiv Receiving a SMS is done through the HTTP the  HTTP API, API,  this a PHP script pointed by Jasmin for every received SMS (using routing): <?php // Rec Receiv eiving ing sim simple ple mes messag sage e usi using ng PHP thr throug ough h HTT HTTP P Post Post // Th This is ex exam ampl ple e wi will ll st stor ore e ev ever ery y re rece ceiv ived ed SM SMS S to a SQ SQL L tabl table e // http://jasminsms http://jasminsms.com .com

$MO_SMS   =   $_POST; $_POST; $db   =   pg_connect( pg_connect('host 'host=127. =127.0.0. 0.0.1 1 port= port=5432 5432 dbna dbname=sm me=sms_de s_demo mo user= user=jasmi jasmin n passw password=j ord=jajapw ajapwd' d'); ); $db) ) if   (!$db // We We'l 'll l no not t AC ACK K th the e me mess ssag age, e, Ja Jasm smin in wi will ll re rese send nd it la late ter  r  die("Er "Error ror con connec nectin ting g to DB" DB"); ); "INSERT INT INTO O sms sms_mo _mo(id (id, , fro from, m, to, cid cid, , pri priori ority, ty, cod coding ing, , val validi idity, ty, con conten tent) t) "; $QUERY   =   "INSERT $QUERY.=   "VALUE $QUERY.= "VALUES S ('% ('%s', s', '%s '%s', ', '%s '%s', ', '%s '%s', ', '%s '%s', ', '%s '%s', ', '%s '%s', ', '%s '%s'); ');" "; $Q   =   sprintf( sprintf($QUERY, $QUERY,   pg_escape_string pg_escape_string( ($MO_SMS $MO_SMS[ ['id' 'id']), ]), pg_escape_string pg_escape_string( ($MO_SMS $MO_SMS[ ['from' 'from']), ]), pg_escape_string pg_escape_string( ($MO_SMS $MO_SMS[ ['to' 'to']), ]), pg_escape_string pg_escape_string( ($MO_SMS $MO_SMS[ ['origin-connector' 'origin-connector']), ]), pg_escape_string( ($MO_SMS $MO_SMS[ ['priority' 'priority']), ]), pg_escape_string pg_escape_string($MO_SMS pg_escape_string( $MO_SMS[ ['coding' 'coding']), ]), pg_escape_string pg_escape_string( ($MO_SMS $MO_SMS[ ['validity' 'validity']), ]), pg_escape_string($MO_SMS pg_escape_string( $MO_SMS[ ['content' 'content']) ]) ); pg_query($Q); pg_query( $Q);

3.8. Programming examples

43

 

Jasmin Documentation, Release 0.9.3-beta

pg_close( ($db); $db); pg_close // Acking Acking bac back k Jas Jasmin min is man mandat datory  ory  echo   "ACK/Jasmin"; "ACK/Jasmin";

In the above example, there’s an error handling where the message is not ACKed if there’s a database connection problem, if it occurs, the script will return “ Error connecting to DB” when Jasmin HTTP thrower is waiting for a “ACL/Jasmin”, this will lead to a message re-queue and later re-deli re-delivery very to the same script, this behaviour is expl explained ained in Processing. Another example of an interactive SMS application: <?php // Wil Will l fil filter ter rec receiv eived ed mes messag sages, es, if the syn syntax tax is cor correc rect t (we (weath ather er <ci <city ty nam name>) e>) // it wi will ll pr prov ovid ide e a `f `fak ake` e` we weat athe her r fo fore reca cast st ba back ck to th the e us user er. . // http://jasminsms http://jasminsms.com .com $MO_SMS   =   $_POST; $_POST; // Acking Acking bac back k Jas Jasmin min is man mandat datory  ory  echo   "ACK/Jasmin"; "ACK/Jasmin"; // Syntax Syntax che check ck if   (!preg_match preg_match( ('/^(w '/^(weath eather) er) (.*)/' )/', ,   $MO_SMS[ $MO_SMS['content'], 'content'],   $matches)) $matches)) "SMS Syn Syntax tax err error, or, ple please ase typ type e 'we 'weath ather er cit city' y' to get a fre fresh sh wea weathe ther r for foreca ecast" st"; ; $RESPONSE   =   "SMS

else

$RESPONSE   =   $martches[ $martches[2]." for foreca ecast: st: Sun Sunny ny 21° 21°C, C, 13K 13Knot nots s NW lig light ht win wind" d"; ; // Sen Send d $RE $RESPO SPONSE NSE bac back k to the use user r ($M ($MO_S O_SMS[ MS['fr 'from' om']) ]) $baseurl   =  'http://127.0.0.1:1401/send' $params   =   '?username=foo' $params.= $params .=   '&password=bar' $params.= $params .=   '&to='. '&to='.urlencode urlencode( ($MO_SMS $MO_SMS[ ['from' 'from']) ]) $params.= '&content='.urlencode urlencode( ($RESPONSE) $RESPONSE) $params.=   '&content='. $response   =   file_get_contents( file_get_contents($baseurl $baseurl. .$params $params); );

Note: // Note: // If yo you u ne need ed to ch chec eck k if th the e me mess ssag age e is re real ally ly de deli live vere red d (o (or r at le leas ast, t, ta take ken n by Ja Jasm smin in fo for r de deli live ver  r  // yo you u must must te test st fo for r $r $res espo pons nse e va valu lue, e, it mu must st be begi gin n wi with th "S "Suc ucce cess ss", ", c. c.f. f. HT HTTP TP AP API I do doc c fo for r mo more re de deta tai i

c.f. c.f. HTTP  HTTP API API for  for more details.

3.8.3 Routin Routing g c.f.   MO router manager   and   MT router manager   for routing routing scenarios scenarios.. c.f.   The message router   for details about routing.

3.9 Mana Management gement CLI CLI overview overview  jCli is Jasmin’s CLI interface, it is an advanced console to manage and configure everyt everything hing needed to start messaging through Jasmin, from users to connectors and message routing management.  jCli is multi-profile multi-profile configurator where it is possible to creat createe a testing, staging and production profiles to hold different different sets of configurations depending on the desired execution environment.

44

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

In order to connect to jCli and start managing Jasmin, the following requirements must be met: • You need a jCli admin aaccount ccount • You need to have a connection to jCli’ jCli’ss tcp port Jasmin management through jCli is done using different modules (users, groups, filters, smpp connectors, http connectors ...), these are detailed in  Management CLI Modules ,  before going to this part, you have to understand how to: •   Configure  jCli to change it’s binding host and port, authentication and logging parameters, •   Authenticate  to jCli and discover basic commands to navigate through the console, •   Know how  to persist to disk the current configuration before restarting or load a specific configuration profile to run test scenarios for example

3.9.1 Arc Architectu hitecture re The Jasmin CLI interface is designed to be a user interactive interface on front of the Perspective brokers provided by Jasmin.

Fig. 3.8: Jasmin CLI arch architecture itecture In the above figure, every Jasmin CLI module (blue boxes) is connected to its perspective broker, and below you find more details on the Perspective brokers used and the actions they are exposing: •  SMPPClientManagerPB  which provides the following actions: 1.   persist: Persist current configuration to disk  2.   load: Load configuration from disk  3.  is_persisted: Used to check if the current configuration is persisted or not 4.   connector_add: Add a SMPP Client connector 5.   connector_remove: Remove a SMPP Client connector 6.  connector_list: List all SMPP Client connectors

3.9. Management CLI overview

45

 

Jasmin Documentation, Release 0.9.3-beta

7.  connector_start: Start a SMPP Client connector 8.  connector_stop: Stop a SMPP Client connector 9.  connector_stopall: Stop all SMPP Client connectors 10.  service_status: Return a SMPP Client connector service status (running or not) 11.  session_state: Return a SMPP Client connector session state (SMPP binding status) 12.  connector_details: Get all details for a gived SMPP Client connector 13.   connector_config: Returns a SMPP Client connector configuration 14.   submit_sm: Send a submit_sm * •   RouterPB which provides the following actions: 1.   persist: Persist current configuration to disk  2.   load: Load configuration from disk  3.  is_persisted: Used to check if the current configuration is persisted or not 4.   user_add: Add a new user 5.  user_authenticate: Authenticate username/password with the existent users * 6.   user_remove: Remove a user 7.   user_remove_all: Remove all users 8.   user_get_all: Get all users 9.  user_update_quota: Update a user quota 10.   group_add: Add a group 11.   group_remove: Remove a group 12.   group_remove_all: Remove all groups 13.  group_get_all: Get all groups 14.  mtroute_add: Add a new MT route 15.  moroute_add: Add a new MO route 16.   mtroute_remove: Remove a MT route 17.   moroute_remove: Remove a MO route 18.  mtroute_flush: Flush MT routes 19.  moroute_flush: Flush MO routes 20.  mtroute_get_all: Get all MT routes 21.  moroute_get_all: Get all MO routes 22.  mtinterceptor_add: Add a new MT interceptor 23.  mointerceptor_add: Add a new MO interceptor 24.   mtinterceptor_remove: Remove a MT interceptor 25.   mointerceptor_remove: Remove a MO interceptor 26.  mtinterceptor_flush: Flush MT interceptor 27.  mointerceptor_flush: Flush MO interceptor

46

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

28.  mtinterceptor_get_all: Get all MT interceptor 29.  mointerceptor_get_all: Get all MO interceptor Note:   (*): These actions are not exposed exposed through jCli

Hint: SMPPClientM SMPPClientManagerPB anagerPB and  RouterPB  are available for third party applications to implement specific business processes, there’s a  FAQ subject including an example  of how an external application can use these Perspective Brokers.

3.9.2 Config Configuration uration The   jasmin.cfg  file  (INI format, located in /etc/jasmin)  contains a  jcli  section where all JCli interface related config elements are: 1 2 3 4 5 6 7

  [jcli]            

bind   port   authentication admin_username # MD5 passwor password d admin_password

=   127.0.0.1 =   8990   =   True   =   jcliadmin digest dig est hex encoded  encoded    =  79e9b0aa3f3e7c53e916f7ac47439bcb

       

log_level   log_file   log_format   log_date_format  

8 9 10 11 12

=   INFO =  /var/log/jasmin/jcli.log =   %(asctime)s %(asctime)s %(lev %(levelnam elname)-8 e)-8s s %(pro %(process cess)d )d %(mes %(message) sage)s s =   %Y-%m-%d %Y-%m-%d %H:%M %H:%M:%S :%S

Table 3.19: [jcli] configuration section

Element bi bind nd port authentication

Default 127. 127.0. 0.0. 0.1 1 8990 True

admin_username admin_password log_*

 jcliadmin  jclipwd

De Description jC jCli li wi will ll only only bi bind nd to th this is spec specifi ified ed ad addr dres ess. s. The binding TCP port. If set to False, anonymous user can connect to jCli and admin user account is no more needed The admin username The admin MD5 crypted password Python’s logging module configuration.

Warning:   Don’t set  authentication to False if you’re not sure about what you are doing

3.9.3 First connection connection & authentication authentication In order to connect to jCli, initiate a telnet session with the hostname/ip and port of jCli as set in  Configuration: telnet telne t 127. 127.0.0.1 0.0.1 8990

And depending on whether  authentication  is set to True or False, you may have to authenticate using the   admin_username  and   admin_passw admin_password ord, here’s an example of an authenticated connection:

3.9. Management CLI overview

47

 

Jasmin Documentation, Release 0.9.3-beta

Authentication required. Username: jcliadmin Password: Welcom Wel come e to Jasmin Jasmin consol console e Type Type help help or ? to list list comm comman ands ds. . Sessio Ses sion n ref ref: : 2 jcli jcli :

Once successfully connected, you’ll get a welcome message, your session id (Session ref) and a prompt (jcli : ) where you can start typing your commands and use  Management CLI Modules.

Available commands: Using tabulation will help you discover the available commands: jcli : [TAB [TABULATI ULATION] ON] persis per sist t loa load d use user r gro group up fil filter ter moi mointe nterce rcepto ptor r mti mtinte nterce rcepto ptor r mor morout outer er mtr mtrout outer er smp smppcc pccm m htt httpcc pccm m qui quit t he

Or type help and you’ll get detailed listing of the available commands with comprehensive descriptions: jcli jcli : help help Available commands: =================== persist load user group filter mo moin inte terc rcep epto tor r mt mtin inte terc rcep epto tor r morouter mtrouter smppccm httpccm

Persist current configuration profile to disk in PROFILE Load configuration PROFILE profile from disk User management Group management Filter management MO In Inte terc rcep epto tor r ma mana nage geme ment nt MT In Inte terc rcep epto tor r ma mana nage geme ment nt MO Router management MT Router management SMPP connector management HTTP client connector management

Control commands: Control commands: ================= quit help

Disconnect from console List available commands with "help" or detailed help with "help cmd".

More detailed help for a specific command can be obtained running  help cmd  where  cmd  is the command you need help for: jcli jcli : help help user user User manag managemen ement t Usage: Usage : user [opt [options] ions] Options: -l, --list -a, --add -u UID, UID, --up --upda date te=U =UID ID -r UID, UID, --re --remo move ve=U =UID ID -s UID UID, , --sh --show ow=U =UID ID

48

List all users or a group users when provided with GID Add user Upda Update te user user usin using g it's it's UID UID Remo Remove ve user user usin using g it's it's UID UID Sh Show ow use user r us usin ing g it it's 's U UID ID

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Interactivity: When running a command you may enter an interactive session, for example, adding a user with  user -a  will start an interactive session where you have to indicate the user parameters, the prompt will be changed from  jcli :   to   > indicating you are in an interactive session: jc jcli li : us user er -a Addi Adding ng a new new User User: : (ok: (ok: save save, , ko: ko: exit exit) ) > use userna rname me foo > pas passwo sword rd bar > uid uid u1 > gid gid g1 > ok Succes Suc cessfu sfully lly added added User User [u1 [u1] ] to Gro Group up [g1 [g1] ]

In the above example, user parameters were  username,  password,  uid  and  gid, note that there’s no order in entering these parameters, and you may use a simple TABULATION to get the parameters you have to enter: ... > [TABU [TABULATI LATION] ON] userna use rname me passwo password rd gid uid ...

3.9.4 Profi Profiles les and persistenc persistence e Everything done using the Jasmin console will be set in runtime memory, and it will remain there until Jasmin is stopped, that’s where persistence is needed to keep the same configuration when restarting.

Persist Typing persist command below will persist runtime configuration configuration to disk using the default profile set in Configuration: jcli : per jcli persis sist t mtrouter mtrou ter configura configuration tion persi persisted sted (prof (profile: ile:jclijcli-prod) prod) smppcc smppc c conf configura iguration tion pers persisted isted (prof (profile:j ile:jclicli-prod) prod) group configurat configuration ion persisted persisted (prof (profile: ile:jclijcli-prod) prod) user confi configura guration tion persi persisted sted (pro (profile: file:jcli jcli-prod -prod) ) httpcc httpc c conf configura iguration tion pers persisted isted (prof (profile:j ile:jclicli-prod) prod) mointerceptor configuration persisted (profile:jcli-prod) (profile:jcli-prod) filter filte r conf configura iguration tion pers persisted isted (prof (profile:j ile:jclicli-prod) prod) mtinterceptor configuration persisted (profile:jcli-prod) (profile:jcli-prod) morouter morou ter configura configuration tion persi persisted sted (prof (profile: ile:jclijcli-prod) prod)

It is possible to persist to a defined profile: jcli jcl i : per persis sist t -p testin testing g

Important:   On Jasmin Jasmin startup, startup,   jcli-prod  profile is automatically loaded, any other profile can only be manually loaded through load -p AnyProfile.

Load Like  persist   command, there’s a  load  command which will loaded a configuration profile from disk, typing  load command below will load the default profil set in Configuration from disk:

3.9. Management CLI overview

49

 

Jasmin Documentation, Release 0.9.3-beta

jcli jcli : load load mtrouter mtrou ter configura configuration tion loade loaded d (prof (profile: ile:jclijcli-prod) prod) smppcc smppc c conf configura iguration tion load loaded ed (prof (profile:j ile:jclicli-prod) prod) group configurat configuration ion loaded loaded (pro (profile: file:jclijcli-prod prod) ) user confi configura guration tion loade loaded d (pro (profile: file:jcli jcli-prod -prod) ) httpcc httpc c conf configura iguration tion load loaded ed (prof (profile:j ile:jclicli-prod) prod) mointercep moint erceptor tor configurat configuration ion loade loaded d (pro (profile: file:jclijcli-prod prod) ) filter filte r conf configura iguration tion load loaded ed (prof (profile:j ile:jclicli-prod) prod) mtinterceptor mtintercep tor configurat configuration ion loade loaded d (pro (profile: file:jclijcli-prod prod) ) morouter morou ter configura configuration tion loade loaded d (prof (profile: ile:jclijcli-prod) prod)

It is possible to load to a defined profile: jcli jcli : load load -p test testin ing g

Note:   When loading a profile, any defined current runtime configuration will lost and replaced by this profile configuration

3.10 Mana Management gement CLI CLI Modules Modules As shown in the architecture figure  Architecture,  jCli is mainly composed of management modules interfacing two Perspective brokers (SMPPClientManagerPB and  RouterPB), each module is identified as a manager of a defined scope: • User management • Group management • etc .. Note: filter and  httpccm modules are not interfacing any Perspective broker, Note: broker, they are facilitating the reuse of created filters filte rs and HTTP Client connector connectorss in MO and MT routers routers,, e.g. a HTTP Client Client connect connector or may be created created once and used many times in MO Routes.

managerr 3.10.1 User manage The User manager module is accessible through the  user command and is providing the following features: Table 3.20:  user command line options

Command -l, -l, –list list -a, –add -e, –enable -d, –disable -u UID, –upda –update=UI te=UID D -r UID, UID, – –remo remove=U ve=UID ID -s UID, UID, –show –show=UI =UID D

Description Li List st all use users or a gr grou oup p use serrs whe when pr pro ovi vide ded d wit with GID GID Add user Enable user Disable user Updat Updatee user user using using iit’ t’ss UID UID Remo Remove ve user user using using it’ it’s UID Show Show use userr using using it’s it’s UID

–smpp-unb –smp p-unbind=U ind=UID –sm –smpppp-ban ban=UI =UID D ID

Unbin Unbind d and userban from smpp serv server er pusing it’s it’ UID Unbind Unb ind user use r fro from m smpp smp serve server r susing usi ng it’ it’s UID

50

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

A User object is required for: •  SMPP Server API authentication API  authentication to send a SMS (c.f.  Sending SMS-MT ) •   HTTP API API authentication  authentication to send a SMS (c.f.  Sending SMS-MT ) • Crea Creating ting a UserFilter using the filter manager (c.f.  Filter manager ) Every User  must  be a member of a Group, so before adding a new User, there must be at least one Group available, Groups are identified by GID  (Group ID). When adding a User, the following parameters are required: •   username: A unique username used for authentication •   password •   uid: A unique identifier, can be same as  username •   gid: Group Identfier •   mt_messaging_cred ( optional): MT Messaging credentials (c.f.  User credentials) Here’s an example of adding a new User to the  marketing group: jc jcli li : us user er -a Addi Adding ng a new new User User: : (ok: (ok: save save, , ko: ko: exit exit) ) > use userna rname me foo > passwo sword rd bar > pas gid market mar keting ing > ui uid d fo foo o > ok Succes Suc cessfu sfully lly added added User User [fo [foo] o] to Gro Group up [ma [marke rketin ting] g]

All the above parameters can be displayed after User creation, except the password: jc jcli li : us user er -s fo foo o username usern ame foo mt_messagi mt_me ssaging_c ng_cred red defaultva defaultvalue lue src_a src_addr ddr None mt_messagi mt_me ssaging_c ng_cred red quota quota http http_thro _throughpu ughput t ND mt_messagi mt_me ssaging_c ng_cred red quota quota bala balance nce ND mt_messagi mt_me ssaging_c ng_cred red quota quota smpp smpps_thr s_throughp oughput ut ND mt_messagi mt_me ssaging_c ng_cred red quota quota sms_ sms_count count ND mt_messagi mt_me ssaging_c ng_cred red quota quota earl early_per y_percent cent ND mt_messagi mt_me ssaging_c ng_cred red valuefilt valuefilter er prior priority ity ^[0-3 ^[0-3]$ ]$ mt_messagi mt_me ssaging_c ng_cred red valuefilt valuefilter er conte content nt .* mt_messagi mt_me ssaging_c ng_cred red valuefilt valuefilter er src_a src_addr ddr .* mt_messagi mt_me ssaging_c ng_cred red valuefilt valuefilter er dst_a dst_addr ddr .* mt_messagi mt_me ssaging_c ng_cred red valuefilt valuefilter er valid validity_ ity_perio period d ^\d+ ^\d+$ $ mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion http http_send _send True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion http http_dlr_ _dlr_meth method od True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion http http_bala _balance nce True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion smpp smpps_sen s_send d True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion prio priority rity True mt_messaging_cred mt_messaging_cre d authorization http_long_content True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion src_ src_addr addr True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion dlr_ dlr_level level True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion http http_rate _rate True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion vali validity_ dity_peri period od True mt_messagi mt_me ssaging_c ng_cred red authoriza authorization tion http http_bulk _bulk False uid foo smpps_cred smpps _cred quota max_bindin max_bindings gs ND

3.10. Management CLI Modules

51

 

Jasmin Documentation, Release 0.9.3-beta

smpps_cred authorizat smpps_cred authorization ion bind True gid marketing marketing

Listing Users will show currently added Users with their UID, GID and Username: jc jcli li : us user er -l #User id #foo

Group id 1

Username foo

Balance MT SMS Throughput ND ND ND/ND

Total Tot al Users: Users: 1

listing a disabled  user,  user, his User id will be prefixed by  ! , same thing apply to group. Note:   When listing

User credentials MT Messaging section

As seen above, User have an optional   mt_messaging_cred parameter which define a set of sections: •   Authorizations: Privileges to send messages and set some defined parameters, •   Value filters: Restrictions on some parameter values (such as source address), •  Default values: Default parameter values to be set by Jasmin when not manually set by User, •   Quotas: Everything about Billing about  Billing,, For each section of the above, there’s keys to be defined when adding/updating a user, the example below show how to set a source address  value filter, a balance of  44.2  44.2,  unlimited sms_count and limit SMS throughput in smpp server to 2 messages per second: jc jcli li : us user er -a Addi Adding ng a new new User User: : (ok: (ok: save save, , ko: ko: exit exit) ) > use userna rname me foo > pas passwo sword rd bar > gid market marketing ing > ui uid d fo foo o > mt_me mt_messag ssaging_c ing_cred red valuefilte valuefilter r src_ src_addr addr ^JAS ^JASMIN$ MIN$ > mt_me mt_messag ssaging_c ing_cred red quota balance 44.2 > mt_me mt_messag ssaging_c ing_cred red quota sms_ sms_count count none > mt_me mt_messag ssaging_c ing_cred red quota smpp smpps_thr s_through oughput put 2 > ok Succes Suc cessfu sfully lly added added User User [fo [foo] o] to Gro Group up [ma [marke rketin ting] g]

 quota. Note:   Setting  none  value to a user quota will set it as  unlimited  quota. In the below tables, you can find exhaustive list of keys for each   mt_messaging mt_messaging_cred _cred section:

52

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.21:  authorization section keys

Key http_send ht http tp_b _bal alan ance ce http_rate http http_b _bul ulk k

Default True Tru ruee True Fal alse se

Description Privilege to send SMS through Sending SMS-MT  Pri Privi vile lege ge to ch chec eck k bala balanc ncee th thro roug ugh h Checking account balance Privilege to check a message rate through Checking rate price Pri Privi vile lege ge to se send nd bul ulks ks th thro roug ugh h htt http api api  (Not implemented yet)

smpps_send htt http_l p_long ong_co _conte ntent nt dlr_level http http_d _dllr_ r_m metho ethod d sr src_ c_ad add dr pr prio iori rity ty vali validit dity_p y_peri eriod od

True Tr True ue True True True True Tr True ue

Privilege to send SMS through SMPP Server API Pri Privil vileg egee to sen send d lon long g conten contentt SMS thr throug ough h  Sending SMS-MT  Privilege to set  dlr-level  parameter (default is 1) Pri Privi vile lege ge to se sett  dlr-method HTTP parameter (default is GET) Pri Privi vile lege ge to de defi fine ned d sou ourrce add ddrress ess of SMSSMS-M MT Pri Privi vile lege ge to de defi fine ned d pri rior orit ity y of SMSSMS-M MT (def default ault is 0) Pri Privil vileg egee to defi defined ned valid validity ity_pe _perio riod d of SMS-MT SMS-MT (de (defa fault ult is NOT NOT SET) SET)

Note:   Authorizations keys keys prefixe prefixed d by http_ or  smpps_ are only applicable for their respective channels.

Table 3.22:  valuefilter section keys

Key sr src_ c_ad add dr

Default .*

Description Re Rege gex x pa pattte tern rn to val aliida datte sour sourcce ad addr dreess of SM SMSS-MT MT

ds dst_ t_ad add dr content pr prio iori rity ty vali validit dity_p y_peri eriod od

.* .* ^[0^[ 0-3] 3]$ $ ^d+$ ^d+$

Re Rege gex x pa pattte tern rn to val aliida datte de dest stin inat atio ion n add ddrress ess of SMSSMS-M MT Regex pattern to validate content of SMS-MT Rege Regex x patt patter ern n to val alid idat atee pr prio iori rity ty of SMSSMS-MT MT Rege Regex x pat patter tern n to vali validat datee vali validit dity_p y_peri eriod od of SMS SMS-M -MT T

Table 3.23:  defaultvalue section keys

Key Default src_addr   None  

Description Default source address of SMS-MT Table 3.24:  quota section keys

Key balance sms_count early_percent http http_t _thr hrou ough ghpu putt smpps_ smp ps_thr throug oughpu hputt

Default ND ND ND ND ND

Description c.f.  1. Balance quota c.f.  2. sms_count quota c.f.   Asynchr Asynchronous onous billing Max. Max. nu numb mber er of me mess ssag ages es pe perr seco second nd to acce accept pt thro throug ugh h HTTP HTTP AP APII Max Max.. num number ber of messag messages es per second second to accept accept thr throug ough h SMPP SMPP Server Server

increment a quota by indicating a sign, ex:  +10 will increment a quota value by 10,  -22.4 will Note:   It is possible to increment decrease a quota value by 22.4.

SMPP Server section

User have an other optional  smpps_cred parameter which define a specialized set of sections for defining his credentials for using the SMPP the SMPP Server API: API: •   Authorizations: Privileges to bind, •   Quotas: Maximum bound connections at a time (multi binding), For each section of the above, there’s keys to be defined when adding/updating a user, the example below show how to authorize binding and set max_bindings to  2:

3.10. Management CLI Modules

53

 

Jasmin Documentation, Release 0.9.3-beta

jc jcli li : us user er -a Addi Adding ng a new new User User: : (ok: (ok: save save, , ko: ko: exit exit) ) > use userna rname me foo > pas passwo sword rd bar > gid market marketing ing > ui uid d fo foo o > smp smpps_ ps_cre cred d aut author horiza izatio tion n bin bind d yes > smp smpps_ ps_cre cred d quo quota ta max_bi max_bindi ndings ngs 2 > ok Succes Suc cessfu sfully lly added added User User [fo [foo] o] to Gro Group up [ma [marke rketin ting] g]

In the below tables, you can find exhaustive list of keys for each  smpps_cred section: Table 3.25:  authorization section keys

Key bi bind nd

Def Default ult Tru ruee

Desc Descri ript ptio ion n Pr Priivi vile lege ge to bi bind nd to SMPP SMPP Serv Server er AP APII Table 3.26:  quota section keys

Key max_bi max _bindi ndings ngs

Default ND

Description Maxim Maximum um bound bound connec connectio tions ns at a tim timee (mult (multii bin bindin ding) g)

increment a quota by indicating indicating a sign, sign, ex:   +10  will increment a quota value by 10,  -2  will Note:   It is possible to increment decrease a quota value by 2.

Group p manager manager 3.10.2 Grou The Group manager module is accessible through the  group command and is providing the following features: Table 3.27:  group command line options

Command -l, –list -a, –add -e, –enable -d, –disable

Description List groups Add group Enable group Disable group

-r GID, GID, – –remo remove=G ve=GID ID Remo Remove ve group group usin using g it it’’s GID A Group object is required for: • Crea Creating ting a User using the  user manager (c.f.  User manager ) • Crea Creating ting a GroupFilter using the filter manager (c.f.  Filter manager ) When adding a Group, only one parameter is required: •   gid: Group Identfier Here’s an example of adding a new Group: jc jcli li : gr grou oup p -a Addi Adding ng a new new Grou Group: p: (ok: (ok: save save, , ko: ko: exit exit) ) > gid market marketing ing > ok Successful Succe ssfully ly added Group [mark [marketing eting] ]

Listing Groups will show currently added Groups with their GID:

54

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jcli jcli : g gro rou up -l #Group #Gr oup id #marketing Total Tot al Groups Groups: : 1

Note:   When listing listing a disabled  group,  group, its group id will be prefixed by  ! .

3.10.3 MO router router manager manager The MO Rou Router ter man manage agerr module module is access accessibl iblee thr throug ough h the morouter com comman mand d and is pro provid viding ing the fol follo lowin wing g featur features: es: Table 3.28:  morouter command line options

Command -l, –list -a, –add -r ORDER, ORDER, –remo –remove=O ve=ORDER RDER -s ORDER, ORDER, –sh –show ow=OR =ORDER DER -f, –flush

Description List MO routes Add a new MO route Remo Remove ve MO MO route route using using it’ it’ss ORDER ORDER Sho Show w MO rou route te usi using ng it’s it’s ORDER ORDER Flush MO routing table

Note:   MO Route is used to route route inbound messages messages (SMS MO) through through two poss possible ible channels: channels: http and smpps (SMPP Server).

MO Router helps managing Jasmin’s MORoutingTable, which is responsible of providing routes to received SMS MO, here are the basics of Jasmin MO routing mechanism: 1.   MORoutingTable holds ordered MORoute objects (each MORoute has a unique order) 2. A MORoute is composed of: •   Filters: One or many filters (c.f.  Filter manager ) •   Connector: One connector (can be  many  in some situations) 3. There’s There’s many objects inheriting inheriting MORoute to provide flexible ways to route messages: •  DefaultRoute: A route without a filter, this one can only set with the lowest order to be a default/fallback  route •  StaticMORoute: A basic route with  Filters and one  Connector •   RandomRoundrobinMORoute RandomRoundrobinMORoute: A route with  Filters  and many  Connectors, will return a random  Connector if its  Filters are matched, can be used as a load balancer route 4. When a SMS MO is rece receiv ived, ed, Jasmin will ask for the right right   MORoute   to consider, all routes are checked in descendant order for their respective  Filters  (when a  MORoute  have many filters, they are checked with an AND boolean operator) 5. When a  MORoute is considered (its  Filters are matching a received SMS MO), Jasmin will use its  Connector to send the SMS MO. Check  The  The message router for router  for more details about Jasmin’s routing. When adding a MO Route, the following parameters are required: •   type: One of the supported MO Routes: DefaultRoute, StaticMORoute, RandomRoundrobinMORoute •   order: MO Route order

3.10. Management CLI Modules

55

 

Jasmin Documentation, Release 0.9.3-beta

When choosing the MO Route  type, additional parameters may be added to the above required parameters. Here’s an example of adding a  DefaultRoute to a HTTP Client Connector (http_default): jcli jcli : moro morout uter er -a Addi Adding ng a new new MO Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Defa DefaultRo ultRoute ute jasmin.routing.Routes.DefaultRout jasmin.routing.R outes.DefaultRoute e arguments: connector > conne connector ctor http http(http (http_def _default) ault) > ok Successful Succe ssfully ly added MORoute MORoute [Def [DefaultR aultRoute] oute] with order order:0 :0

Note:   You don’t have to set order  parameter when the MO Route type is  DefaultRoute, it will be automatically set to 0

Here’s an example of adding a  StaticMORoute StaticMORoute  to a HTTP Client Connector (http_1): jcli jcli : moro morout uter er -a Addi Adding ng a new new MO Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Stat StaticMOR icMORoute oute jasmin.routing.Routes.StaticMORou jasmin.routing.R outes.StaticMORoute te arguments: filters, filte rs, connector connector > or orde der r 10 > fil filter ters s fil filter ter_1 _1 > conne connector ctor http http(http (http_1) _1) > ok Successful Succe ssfully ly added MORoute MORoute [Sta [StaticMO ticMORoute Route] ] with order order:10 :10

Here’s an example of adding a  StaticMORoute StaticMORoute  to a SMPP Server user (user_1): jcli jcli : moro morout uter er -a Addi Adding ng a new new MO Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Stat StaticMOR icMORoute oute jasmin.routing.Routes.StaticMORou jasmin.routing.R outes.StaticMORoute te arguments: filters, filte rs, connector connector > or orde der r 15 > fil filter ters s fil filter ter_2 _2 > conne connector ctor smpp smpps(use s(user_1) r_1) > ok Successful Succe ssfully ly added MORoute MORoute [Sta [StaticMO ticMORoute Route] ] with order order:15 :15

Note:   When rout routing ing to a smpps smpps connector connector like the above above example example the  user_1   designates the   username  of the concerned user, if he’s already bound to Jasmin’s  SMPP Server API routed API  routed messages will be delivered to him, if not, queuing will take care of delivery.

Here’s an example of adding a  RandomRoundrobinMORoute RandomRoundrobinMORoute to two HTTP Client Connectors (http_2 and http_3): jcli jcli : moro morout uter er -a Addi Adding ng a new new MO Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Rand RandomRou omRoundrob ndrobinMO inMORoute Route jasmin.routing.Routes.RandomRound jasmin.routing.R outes.RandomRoundrobinMORoute robinMORoute arguments: filters, connectors > filte filters rs filter_3; filter_3;filte filter_1 r_1 > connectors http(http_2);http(http_3) > or orde der r 20

56

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

> ok Successful Succe ssfully ly added MORoute MORoute [Ran [RandomRo domRoundro undrobinM binMORout ORoute] e] with orde order:20 r:20

is po poss ssib ible le to to use use a   RoundRobinMORoute   with with a mix of connec connector tors, s, exa exampl mple: e:   connectors Note:   It is smpps(user_1);http(http_1);http(http_3). Once the above MO Routes are added to  MORoutingTable, it is possible to list these routes: jcli jcli : moro morout uter er -l #Order Type #2 #20 0 Ra Rand ndom omRo Roun undr drob obin inMO MORo Rout ute e #15 StaticMORoute #10 StaticMORoute #0 DefaultRoute Tota Total l MO Rout Routes es: : 3

Connector ID(s) ht http tp(h (htt ttp_ p_2) 2), , ht http tp(h (htt ttp_ p_3) 3) smpps(user_1) http(http_1) http(http_default)

Filter(s) <T <T>, >, <T <T> > <T> <T>

 and HTTP Client  Note:   Filters and Connectors were created created before creating these routes, please check  Filter   Filter manager  and connector manager  for  for further details It is possible to obtain more information of a defined route by typing  moroute -s <order>: jcli jcli : moro morout uter er -s 20 RandomRoun Rando mRoundrob drobinMOR inMORoute oute to 2 conn connector ectors: s: - http(http http(http_2) _2) - http(http http(http_3) _3) jcli jcli : moro morout uter er -s 10 StaticMORo Stati cMORoute ute to http(http_ http(http_1) 1) jcli jcli : moro morout uter er -s 0 DefaultRou Defau ltRoute te to http(http http(http_defa _default) ult)

More control commands: •  morouter -r <order>: Remove route at defined order  •  morouter -f : Flush MORoutingTable MORoutingTable (unrecoverable)

3.10.4 MT router router manager manager The MT Router manager module is accessible through the  mtrouter command and is providing the following features: Table 3.29:  mtrouter command line options

Command -l, –list -a, –add -r ORDER, ORDER, –remo –remove=O ve=ORDER RDER -s ORDER, ORDER, –sh –show ow=OR =ORDER DER -f, –flush

Description List MT routes Add a new MT route Remo Remove ve MT MT route route using using it’ it’ss ORDER ORDER Sho Show w MT route route using using it it’’s ORDER ORDER Flush MT routing table

Note:   MT Route is used to route outbound messages (SMS MT) thro through ugh one channel: smppc (SMPP Client).

3.10. Management CLI Modules

57

 

Jasmin Documentation, Release 0.9.3-beta

MT Router helps managing Jasmin’s Jasmin’s MTRoutingTable, MTRoutingTable, which is responsible of providing routes to outgoing SMS MT, here are the basics of Jasmin MT routing mechanism: 1.   MTRoutingTable holds ordered MTRoute objects (each MTRoute has a unique order) 2. A MTRoute is composed of: •   Filters: One or many filters (c.f.  Filter manager ) •   Connector: One connector (can be  many  in some situations) •   Rate: For billing billing purpose, purpose, the rate of sending one message thro through ugh this route; it can be zero to mark the route as FREE (NOT RATED) (c.f. Billing (c.f.  Billing)) 3. There’s There’s many objects inheriting inheriting MTRoute to provide flexible ways to route messages: •  DefaultRoute: A route without a filter, this one can only set with the lowest order to be a default/fallback  route •  StaticMTRoute: A basic route with  Filters and one  Connector •   RandomRoundrobinMTRoute RandomRoundrobinMTRoute: A route with  Filters  and many  Connectors, will return a random  Connector if its  Filters are matching, can be used as a load balancer route 4. When a SMS MT is to be sent, sent, Jasmin will ask for the right right  MTRoute  to consider, all routes are checked in descendant order for their respective  Filters  (when a  MTRoute  have many filters, they are checked with an AND boolean operator) 5. When When a MTRoute is considered (its  Filters are matching an outgoing SMS MT), Jasmin will use its  Connector to send the SMS MT. Check  The  The message router for router  for more details about Jasmin’s routing. When adding a MT Route, the following parameters are required: •   type: One of the supported MT Routes: DefaultRoute, StaticMTRoute, RandomRoundrobinMTRoute •   order: MO Route order •   rate: The route rate, can be zero When choosing the MT Route  type, additional parameters may be added to the above required parameters. Here’s an example of adding a  DefaultRoute to a SMPP Client Connector (smppcc_default): jcli jcli : mtro mtrout uter er -a Addi Adding ng a new new MT Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Defa DefaultRo ultRoute ute jasmin.routing.Routes.DefaultRout jasmin.routing.R outes.DefaultRoute e arguments: connector > conne connector ctor smpp smppc(smp c(smppcc_ pcc_defau default) lt) > ra rate te 0. 0.0 0 > ok Successful Succe ssfully ly added MTRoute MTRoute [Def [DefaultR aultRoute] oute] with order order:0 :0

Note:   You don’t have to set order  parameter when the MT Route type is  DefaultRoute, it will be automatically set to 0

Here’s an example of adding a  StaticMTRoute StaticMTRoute  to a SMPP Client Connector (smppcc_1): jcli jcli : mtro mtrout uter er -a Addi Adding ng a new new MT Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Stat StaticMTR icMTRoute oute

58

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jasmin.routing.Routes.StaticMTRoute jasmin.routing.Routes.StaticMTRou te arguments: filters, filte rs, connector connector > filte filters rs filter_1; filter_1;filte filter_2 r_2 > or orde der r 10 > conne connector ctor smpp smppc(smp c(smppcc_ pcc_1) 1) > ra rate te 0. 0.0 0 > ok Successful Succe ssfully ly added MTRoute MTRoute [Sta [StaticMT ticMTRoute Route] ] with order order:10 :10

Here’s an example of adding a   RandomRoundrobinMTRoute to two SMPP Client Connectors (smppcc_2 and smppcc_3): jcli jcli : mtro mtrout uter er -a Addi Adding ng a new new MT Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > or orde der r 20 > type Rand RandomRou omRoundrob ndrobinMT inMTRoute Route jasmin.routing.Routes.RandomRound jasmin.routing.R outes.RandomRoundrobinMTRoute robinMTRoute arguments: filters, connectors > fil filter ters s fil filter ter_3 _3 > connectors smppc(smppcc_2);smppc(smppcc_ smppc(smppcc_2);smppc(smppcc_3) 3) > ra rate te 0. 0.0 0 > ok Successful Succe ssfully ly added MTRoute MTRoute [Ran [RandomRo domRoundro undrobinM binMTRout TRoute] e] with orde order:20 r:20

Once the above MT Routes are added to  MTRoutingTable, it is possible to list these routes: jcli jcli : mtro mtrout uter er -l #Order Type #2 #20 0 Ra Rand ndom omRo Roun undr drob obin inMT MTRo Rout ute e #10 S St taticMTRoute #0 DefaultRoute Tota Total l MT Rout Routes es: : 3

Rate 0 (! (!) ) 0 (!) 0 (!)

Connector ID(s) sm smpp ppc( c(sm smpp ppcc cc_2 _2), ), sm smpp ppc( c(sm smpp ppcc cc_3 _3) ) smppc(smppcc_1) sm smppc(smppcc_default)

Filter(s) <T <T> > <T>, <T>

Note:   Filters and Connectors were created created before creating these routes, please check   Filter Filter manager  and  and HTTP Client  connector manager  for  for further details

It is possible to obtain more information of a defined route by typing  mtroute -s <order>: jcli jcli : mtro mtrout uter er -s 20 RandomRoun Rando mRoundrob drobinMTR inMTRoute oute to 2 conn connector ectors: s: - smppc(smp smppc(smppcc_2 pcc_2) ) - smppc(smp smppc(smppcc_3 pcc_3) ) NOT RATED RATED jcli jcli : mtro mtrout uter er -s 10 StaticMTRo Stati cMTRoute ute to smppc(smpp smppc(smppcc_1 cc_1) ) NOT RATED jcli jcli : mtro mtrout uter er -s 0 DefaultRou Defau ltRoute te to smppc(smp smppc(smppcc_d pcc_defaul efault) t) NOT RATED

More control commands: •  mtrouter -r <order>: Remove route at defined  order  •  mtrouter -f : Flush MTRoutingTabl MTRoutingTablee (unrecove (unrecoverable) rable)

3.10. Management CLI Modules

59

 

Jasmin Documentation, Release 0.9.3-beta

interceptor manager manager 3.10.5 MO interceptor The MO Interceptor manager module is accessible through the   mointercept mointerceptor or  command and is providing the following features: Table 3.30:   mointerceptor command line options

Command -l, –list -a, –add -r ORDER, ORDER, –re –remov move=ORD e=ORDER ER -s ORDER, –show=ORD –show=ORDER ER -f, –flush

Description List MO interceptors Add a new MO interceptors Remo Remove ve MO inte intercept rceptor or using using it’ it’ss ORDER Show Show MO inte intercept rceptor or usin using g it’ it’ss ORDER Flush MO interception table

messages (SMS MO) to a user defined script, check  Interception for  Interception  for Note:   MO Interceptor is used to hand inbound messages more details. MO Interceptor helps managing Jasmin’ Jasmin’ss MOInterceptionTable, MOInterceptionTable, which is responsible of intercepting SMS MO before routing is made, here are the basics of Jasmin MO interception mechanism: 1.   MOInterceptionTable holds ordered  MOIntercep MOInterceptor tor objects (each MOInterceptor has a unique order) 2. A  MOInterceptor is composed of: •   Filters: One or many filters (c.f.  Filter manager ) •   Script: Path to python script 3. There’s There’s many objects inheriting inheriting  MOInterceptor to provide flexible ways to route messages: •   DefaultInterceptor: An interceptor interceptor without without a filter, filter, this one can only set with the lowes lowestt order to be a default/fallback default/f allback interceptor •  StaticMOInterceptor: A basic interceptor with  Filters and one  Script 4. When a SMS MO is received, received, Jasmin Jasmin will ask for the right  MOInterceptor   to consider, all interceptors are checked in descendant order for their respective  Filters  (when a   MOInterceptor   have many filters, they are checked with an  AND  boolean operator) 5. When When a MOInterceptor is considered (its  Filters are matching a received received SMS MO), Jasmin will call its  Script with the Routable argument. Jasmin’s interceptor. Check   Interception for Interception for more details about Jasmin’s When adding a MO Interceptor, the following parameters are required: •   type: One of the supported MO Interceptors: DefaultInterceptor, StaticMOInterceptor •   order: MO Interceptor order When choosing the MO Interceptor  type, additional parameters may be added to the above required parameters. Here’s an example of adding a  DefaultInterceptor DefaultInterceptor to a python script: jcli : moi jcli mointe nterce rcepto ptor r -a Adding Add ing a new MO Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Defa DefaultIn ultInterce terceptor ptor <class 'jasmin.routing 'jasmin.routing.Interceptors.Def .Interceptors.DefaultInterceptor'> aultInterceptor'> arguments: script > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mo-interc ception/mo-interceptor.py) eptor.py) > ok Successful Succe ssfully ly added MOInterce MOInterceptor ptor [Defa [DefaultI ultInterc nterceptor eptor] ] with order order:0 :0

60

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

now, only python2 script is permitted. Note:   As of now,

Note:   Pay atten attention tion that the given given script is copied to Jasmin core, do not expec expectt Jasmin to refresh the scrip scriptt code when you update it, you’ll need to redefine the   mointerceptor  rule  rule again so Jasmin will refresh the script.

Note:   You don’t have to set order  parameter when the MO Interceptor type is   DefaultInterceptor, it will be automatically set to 0

Here’s an example of adding a  StaticMOInterceptor StaticMOInterceptor to a python script: jcli : moi jcli mointe nterce rcepto ptor r -a Adding Add ing a new MO Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Stat StaticMOI icMOInterc ntercepto eptor r <class 'jasmin.routing 'jasmin.routing.Interceptors.Sta .Interceptors.StaticMOInterceptor' ticMOInterceptor'> > arguments: filters, filte rs, script script > or orde der r 10 > fil filter ters s fil filter ter_1 _1 > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mo-interc ception/mo-interceptor.py) eptor.py) > ok Successful Succe ssfully ly added MOInterce MOInterceptor ptor [Stat [StaticMO icMOInter Intercepto ceptor] r] with orde order:10 r:10

Once the above MO Interceptors are added to  MOInterceptionTable, it is possible to list these interceptors: jcli : moi jcli mointe nterce rcepto ptor r -l #Order Type #10 StaticMOInterceptor #0 DefaultInterceptor Total Tot al MO Interc Intercept eptors ors: : 2

Script <MOIS (pyCode= ..)> <MOIS (pyCode= ..)>

Filter(s) <T>

 for further details Note:   Filters were created before creating these interceptors, interceptors, please check  Filter   Filter manager  for It is possible to obtain more information of a defined interceptor by typing  mointerceptor -s <order>: jcli : moi jcli mointe nterce rcepto ptor r -s 10 StaticMOInterceptor/<MOIS StaticMOIntercep tor/<MOIS (pyCode= ..)> jcli : moi jcli mointe nterce rcepto ptor r -s 0 DefaultInterceptor/<MOIS DefaultIntercept or/<MOIS (pyCode= ..)>

More control commands: •  mointerceptor -r <order>: Remove interceptor at defined  order  •  mointerceptor -f : Flush MOInterceptionTable MOInterceptionTable (unrecoverable)

interceptor manager manager 3.10.6 MT interceptor The MT Interceptor manager module is accessible through the  mtinterceptor command and is providing the following features:

3.10. Management CLI Modules

61

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.31:   mtinterceptor command line options

Command -l, –list -a, –add -r ORDER, ORDER, –re –remov move=ORD e=ORDER ER -s ORDER, –show=ORD –show=ORDER ER

Description List MT interceptors Add a new MT interceptors Remo Remove ve MT intercept interceptor or using using it’ it’ss ORDER Show Show MT intercep interceptor tor using it’ it’ss ORDER

-f, –flush

Flush MT interception table

Note:   MT Interceptor is used to hand outbound messages messages (SMS MT) to a user defined script, check   Interception for Interception  for more details.

MT Interceptor helps managing Jasmin’s MTInterceptionTable, which is responsible of intercepting SMS MT before routing is made, here are the basics of Jasmin MT interception mechanism: 1.   MTInterceptionTable holds ordered  MTInterceptor objects (each MTInterceptor has a unique order) 2. A  MTInterceptor is composed of: •   Filters: One or many filters (c.f.  Filter manager ) •   Script: Path to python script 3. There’s There’s many objects inheriting inheriting  MTInterceptor to provide flexible ways to route messages: •   DefaultInterceptor: An interceptor interceptor without without a filter, filter, this one can only set with the lowes lowestt order to be a default/fallback default/f allback interceptor •  StaticMTInterceptor: A basic interceptor with  Filters and one  Script 4. When a SMS MT is received, received, Jasmin Jasmin will ask for the right  MTInterceptor   to consider, all interceptors are checked in descendant order for their respective  Filters  (when a   MTIntercep MTInterceptor tor  have many filters, they are checked with an  AND  boolean operator) 5. When a MTInterceptor is considered (its  Filters are matching a received SMS MT), Jasmin will call its  Script with the Routable argument. Jasmin’s interceptor. Check  Interception for  Interception for more details about Jasmin’s When adding a MT Interceptor, the following parameters are required: •   type: One of the supported MT Interceptors: DefaultInterceptor, StaticMTInterceptor •   order: MT Interceptor order When choosing the MT Interceptor  type, additional parameters may be added to the above required parameters. Here’s an example of adding a  DefaultInterceptor DefaultInterceptor to a python script: jcli : mti jcli mtinte nterce rcepto ptor r -a Adding Add ing a new MT Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Defa DefaultIn ultInterce terceptor ptor <class 'jasmin.routing 'jasmin.routing.Interceptors.Def .Interceptors.DefaultInterceptor'> aultInterceptor'> arguments: script > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mt-interc ception/mt-interceptor.py) eptor.py) > ok Successful Succe ssfully ly added MTInterce MTInterceptor ptor [Defa [DefaultI ultInterc nterceptor eptor] ] with order order:0 :0

Note:   As of now, now, only python2 script is permitted.

62

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

attention tion that the given given script is copied to Jasmin core, do not expec expectt Jasmin to refresh the scrip scriptt code Note:   Pay atten when you update it, you’ll need to redefine the   mtinterceptor  rule  rule again so Jasmin will refresh the script.

Note:   You don’t have to set order  parameter when the MT Interceptor type is   DefaultInterceptor, it will be automatically set to 0

Here’s an example of adding a  StaticMTInterceptor StaticMTInterceptor to a python script: jcli : mti jcli mtinte nterce rcepto ptor r -a Adding Add ing a new MT Int Interc ercept eptor: or: (ok (ok: : sav save, e, ko: exit) > type Stat StaticMTI icMTInterc ntercepto eptor r <class 'jasmin.routing 'jasmin.routing.Interceptors.Sta .Interceptors.StaticMTInterceptor' ticMTInterceptor'> > arguments: filters, filte rs, script script > or orde der r 10 > fil filter ters s fil filter ter_1 _1 > script python2(/opt/jas python2(/opt/jasmin-scripts/inter min-scripts/interception/mt-interc ception/mt-interceptor.py) eptor.py) > ok Successful Succe ssfully ly added MTInterce MTInterceptor ptor [Stat [StaticMT icMTInter Intercepto ceptor] r] with orde order:10 r:10

Once the above MT Interceptors are added to  MTInterceptionTable, it is possible to list these interceptors: jcli : mti jcli mtinte nterce rcepto ptor r -l #Order Type #10 StaticMTInterceptor #0 DefaultInterceptor Total Tot al MT Interc Intercept eptors ors: : 2

Script <MTIS (pyCode= ..)> <MTIS (pyCode= ..)>

Filter(s) <T>

interceptors, please check  Filter   Filter manager  for  for further details Note:   Filters were created before creating these interceptors, It is possible to obtain more information of a defined interceptor by typing  mtinterceptor -s <order>: jcli : mti jcli mtinte nterce rcepto ptor r -s 10 StaticMTInterceptor/<MTIS StaticMTIntercep tor/<MTIS (pyCode= ..)> jcli jcl i : mti mtinte nterce rcepto ptor r -s 0 DefaultInterceptor/<MTIS DefaultIntercept or/<MTIS (pyCode= ..)>

More control commands: •  mtinterceptor -r <order>: Remove interceptor at defined  order  •  mtinterceptor -f : Flush MTInterceptionT MTInterceptionTable able (unrecove (unrecoverable) rable)

3.10.7 SMPP Client Client connector connector manager The SMPP Client connector manager module is accessible through the  smppccm  command and is providing the following features:

3.10. Management CLI Modules

63

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.32:  smppccm command line options

Command -l, –list -a, –add -u CID, CID, –update=CI –update=CID D -r CID, CID, –remove –remove=CID =CID

Description List SMPP connectors Add SMPP connector Updat Updatee SMPP conne connector ctor config configurat uration ion using using it it’s ’s CID Remo Remove ve SMPP SMPP con connect nector or using using it’ it’ss CID

-s CID, CID, – –sho show=C w=CID ID -1 CID, CID, –start –start=CI =CID D -0 CID, CID, –stop= –stop=CID CID

Sho Show wS SMPP MPP con connec nector tor usi using ng it’s it’s CID Start Start SMP SMPP P con connec nector tor usi using ng it’s it’s CID Start Start SMP SMPP P con connec nector tor usi using ng it’s it’s CID

A SMPP Client connector is used to send/receive SMS through SMPP v3.4 protocol, it is directly connected to MO and MT routers to provide end-to-end message delivery. Adding a new SMPP Client connector requires knowledge of the parameters detailed in the listing below:

Parameter cid logfile logrotate loglevel

Description Connector ID (must be unique)

     

host     port   ssl username password bind   bind_to   trx_to   res_to   pdu_red_to   con_loss_retry   con_loss_delay   con_fail_retry   con_fail_delay   src_addr   src_ton   src_npi   dst_ton   dst_npi   bind_ton   bind_npi   validity     priority   requeue_delay   addr_range   systype   dlr_expiry submit_throughput   proto_id coding

64

 

 

When to rotate the log file, possible values: S=Seconds, M=Minutes, H=Hours, D=Days, W0-W6=Weekday W0-W6=Weekday ( Logging numeric level: 10=DEBUG, 20=INFO, 30=WARNING, 30=WARNING, 40=ERROR, 50=CRITICCAL Server that runs SMSC The port number for the connection to the SMSC. Activate Activate ssl connection

Bind type: transceiver, transceiver, receiver receiver or transmitter transmitter Timeout for response to bind request Maximum time lapse allowed between transactions, after which, the connection is considered as inactiv inactivee and Timeout for responses to any request PDU Timeout for reading a single PDU, this is the maximum lapse of time between receiving receiving PDU’s header and its Reconnect on connection loss ? (yes, no) Reconnect delay on connection loss (seconds) Reconnect on connection failure ? (yes, no) Reconnect delay on connection failure (seconds)

Default source adress of each SMS-MT if not set while sending it, can be numeric or alphanumeric, when not Source address TON setting for the link: 0=Unknown, 1=International, 1=International, 2=National, 3=Network specific, 4=S Source address NPI setting for the link: 0=Unknown, 1=ISDN, 3=Data, 4=T 4=Telex, elex, 6=Land mobile, 8=National Destination address TON setting for the link: 0=Unknown, 1=International, 1=International, 2=National, 3=Network specific, Destination address NPI setting for the link: 0=Unknown, 1=ISDN, 3=Data, 4=Telex, 4=Telex, 6=Land mobile, 8=Nati Bind address TON setting for the link: 0=Unknown, 1=International, 1=International, 2=National, 3=Network specific, 4=Sub Bind address NPI setting for the link: 0=Unknown, 1=ISDN, 3=Data, 4=Telex, 4=Telex, 6=Land mobile, 8=National, 9 Default validity validity period of each SMS-MT if not set while sending it, when not defined it will take SMSC defau SMS-MT default priority if not set while sending it: 0, 1, 2 or 3 Delay to be considered when requeuing a rejected message Indicates which MS’ MS’ss can send messages to this connector connector,, seems to be an informati informative ve value The system_type parameter is used to categorize the type of ESME that is binding to the SMSC. Examples in When a SMS-MT is not acked, it will remain waiting in memory for  dlr_expiry  seconds, after this period, any Active SM SMS-MT S-MT throttling throttling in MPS (Messages per second), set to 0 (zero) ffor or unlimited throughput throughput Used to indicate protocol id in SMS-MT and SMS-MO Default coding of each SMS-MT if not set while sending it: 0=SMSC Default, 1=IA5 ASCII, 2=Octet unspec

Chapter 3. Full contents

64

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Parameter   elink_interval def_msg_id   ripf    dlr_msgid  

Description Enquire link interval (seconds) Specifies the SMSC index of a pre-defined (‘canned’) message. Replace if present flag: 0=Do not replace, 1=Replace Indicates how to read msg id when receivin receiving g a receipt: 0=msg id is identical in submit_sm_r submit_sm_resp esp and deliver_s deliver_s

connector, only it’ it’ss  cid  is required, all the other parameters will be set to their Note:   When adding a SMPP Client connector, respectivee defaults. respectiv

Note:   Connector restart is require required d only when changing the following parameters: parameters:  host, port,  username,  password, systemType,  logfile,  loglevel; any other change is applied without requiring connector to be restarted.

Here’s an example of adding a new  transmitter SMPP Client connector with  cid=Demo: jcli jcli : smpp smppcc ccm m -a Adding Add ing a new connecto connector: r: (ok (ok: : sav save, e, ko: exit) > ci cid d De Demo mo > bin bind d tra transm nsmitt itter er > ok Successful Succe ssfully ly added connector connector [Dem [Demo] o]

All the above parameters can be displayed after connector creation: jcli jcli : smpp smppcc ccm m -s Demo Demo ripf ripf 0 con_fail_d con_f ail_delay elay 10 dlr_expiry dlr_e xpiry 86400 coding cod ing 0 submit_throughput submit_throughpu t 1 elink_inte elink _interval rval 10 bind_t bin d_to o 30 port por t 277 2775 5 con_fail_r con_f ail_retry etry yes password passw ord password password src_addr None src_addr bind_npi bind_ npi 1 addr_range addr_ range None dst_to dst _ton n 1 res_to res _to 60 def_msg_id def_m sg_id 0 priority prior ity 0 con_loss_r con_l oss_retry etry yes username smppclient dst_np dst _npi i 1 validity valid ity None requeue_de reque ue_delay lay 120 host 127.0 127.0.0.1 .0.1 src_np src _npi i 1 trx_to trx_t o 300 logfile /var/log/jasmin/default-Demo.log /var/log/jasmin/default-Demo.log systype cid Demo Demo loglevel logle vel 20

3.10. Management CLI Modules

65

 

Jasmin Documentation, Release 0.9.3-beta

bind trans transmitt mitter er proto_id proto _id None con_loss_d con_l oss_delay elay 10 bind_ton bind_ ton 0 pdu_red_to pdu_r ed_to 10 src_to src _ton n 2

Note:   From the example above, you can see that showing a connector details will return all it’s parameters even even those you did not enter while creating/updating the connector, they will take their respective default values as explained in SMPP Client connector parameters

Listing connectors will show currently added SMPP Client connectors with their CID, Service/Session state and start/stop counters: jcli jcli : smpp smppcc ccm m -l #Connector id #888 #Demo Total connectors: connectors: 2

Service Session stopped None stopped None

Starts Stops 0 0 0 0

Updating an existent connector is the same as creating a new one, simply type  smppccm -u <cid>  where  cid  is the connector id you want to update, you’ll run into a new interactive session to enter the parameters you want to update (c.f.  SMPP Client connector parameters). Here’s an example of updating SMPP Client connector’s host: jcli jcli : smpp smppcc ccm m -u Demo Demo Updati Upd ating ng connec connector tor id [De [Demo] mo]: : (ok (ok: : sav save, e, ko: exi exit) t) > hos host t 10. 10.10. 10.1.2 1.2 > ok Successful Succe ssfully ly updated updated connector connector [Demo [Demo] ]

More control commands: •  smppccm -1 <cid>: Start connector and try to connect •  smppccm -0 <cid>: Stop connector and disconnect •  smppccm -r <cid>: Remove connector (unrecoverable) (unrecoverable)

3.10.8 Filter manage managerr The Filter manager module is accessible through the  filter command and is providing the following features: Table 3.34:  filter command line options

Command -l, –list -a, –add -r FID, FID, – –remo remove= ve=FID FID -s FID, FID, –sh –show ow=FI =FID D

Description List filters Add filter Remo Remove ve filter filter using using it it’’s FID FID Show Show filt filter er usi using ng it’s it’s FID

Filters are used by MO/MT routers to help decide on which route a message must be delivered, the following flowchart provides details of the routing process: Jasmin provides many Filters offering advanced flexibilities to message routing:

66

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.9: Routi Routing ng process process flo flow w

3.10. Management CLI Modules

67

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.35: Jasmin Filters Filters

Name

Routes All All MO MT MT

Description This This filte filterr will will al alwa ways ys ma matc tch h any any me mess ssag agee crit criter eria ia Wil illl ma matc tch h th thee sour source ce conn connec ecto torr of a me mess ssag agee Wil illl ma matc tch h th thee own wner er of a MT me mess ssag agee Wil illl ma matc tch h th thee owne owner’ r’ss gr grou oup p of a MT me mess ssag agee

 

All All All All

Wil illl ma matc tch h th thee sour source ce addr addres esss of a MO me mess ssag agee Wil illl ma matc tch h th thee sour source ce addr addres esss of a me mess ssag agee

     

Al Alll Al Alll Al Alll All All All

Wil illl ma matc tch h th thee co cont nten entt of a mess messag agee Wil illl ma matc tch h th thee date date of a mess messag agee Wil illl ma matc tch h th thee ti time me of a mess messag agee Wil illl chec check k if me mess ssag agee ha hass a de defin fined ed tag tag Will pass pass the me messa ssage ge to a third third par party ty python python script script for useruser-defi defined ned filt filteri ering ng

TransparentFilter   ConnectorFilter   UserFilter   GroupFilter   SourceAddrFilter DestinationAddrFilter ShortMessageFilter DateIntervalFilter TimeIntervalFilter   TagFilter   EvalPyFilter

Check  The  The message router for router  for more details about Jasmin’s routing. When adding a Filter, the following parameters are required: •   type: One of the supported Filters: TransparentFilter, ConnectorFilter, UserFilter, GroupFilter, SourceAddrFilter, DestinationAddrFilter, ShortMessageFilter, DateIntervalFilter, TimeIntervalFilter, TagFilter, EvalPyFilter •   fid: Filter id (must be unique) When choosing the Filter  type, additional parameters may be added to the above required parameters: Table 3.36: Filters parameters parameters

Name

Example   TransparentFilter ConnectorFilter   smpp-01   bobo UserFilter GroupFilter   partners SourceAddrFilter   ^20d+ DestinationAddr^85111$ Filter ShortMessageFilter

^hello.*$

 

Parameters No parameters are required cid of the connector to match uid of the user to match gid of the group to match source_addr: Regular expression to match source address destination_addr: Regular expression to match destination address

 

short_message: Regular expression to match message content

       

DateIntervalFilter   2014-09-18;2014dateInterval: Two dates separated by ; (date format is 09-28 YYYY-MM-DD) TimeIntervalFilter   08:00:00;18:00:00   timeInterval: Two timestamps separated by ; (timestamp format is HH:MM:SS)   32401 TagFilter   tag:  numeric  tag to match in message   /root/thirdparty.py   pyCode: Path to a python script, ( script,  ( External business logic  for more EvalPyFilter details)

Here’s an example of adding a  TransparentFilter jcli jcli : filt filter er -a Addi Adding ng a new new Filt Filter er: : (ok: (ok: save save, , ko: ko: exit exit) ) type typ e fid > type tran transpare sparentfil ntfilter ter > fid fid TF > ok Successful Succe ssfully ly added Filter Filter [Tra [Transpar nsparentF entFilter ilter] ] with fid:T fid:TF F

Here’s an example of adding a  SourceAddrFilter SourceAddrFilter

68

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

jcli jcli : filt filter er -a Addi Adding ng a new new Filt Filter er: : (ok: (ok: save save, , ko: ko: exit exit) ) > type sour sourceadd ceaddrfilt rfilter er jasmin.routing.Filters.SourceAddr jasmin.routing.F ilters.SourceAddrFilter Filter arguments: source_addr > sourc source_ad e_addr dr ^20\d+ ^20\d+ > ok You must must set these these option options s bef before ore sav saving ing: : typ type, e, fid fid, , sou source rce_ad _addr dr > fid fid From From20 20* > ok Successful Succe ssfully ly added Filter Filter [Sou [SourceAd rceAddrFi drFilter] lter] with fid:F fid:From2 rom20 0*

Here’s an example of adding a   TimeIntervalFilter jcli jcli : filt filter er -a Addi Adding ng a new new Filt Filter er: : (ok: (ok: save save, , ko: ko: exit exit) ) > fid Workin WorkingHo gHours urs > type time timeinter intervalfi valfilter lter jasmin.routing.Filters.TimeInterv jasmin.routing.F ilters.TimeIntervalFilter alFilter arguments: timeInterval > timeI timeInter nterval val 08:00:00; 08:00:00;18:0 18:00:00 0:00 > ok Successful Succe ssfully ly added Filter Filter [Tim [TimeInte eInterval rvalFilte Filter] r] with fid: fid:Worki WorkingHou ngHours rs

It is possible to list filters with: jcli jcli : filt filter er -l #Filter id #Sta #Start rtWi With thHe Hell llo o #ExternalPy #T #To8 o851 5111 11 #Sep #Septe temb mber er20 2014 14 #Wor #Worki king ngHo Hour urs s #TF #TG-Spain-Vodacom #From20*   Total Tot al Filter Filters: s: 7

Type Shor ShortM tMes essa sage geFi Filt lter er EvalPyFilter De Dest stin inat atio ionA nAdd ddrF rFil ilte ter r Date DateIn Inte terv rval alFi Filt lter er Time TimeIn Inte terv rval alFi Filt lter er TransparentFilter TagFilter So Sour urce ceAd Addr drFi Filt lter er

Routes MO MT MO MT MO MT MO MT MO MT MO MT MO MT MO

Description <Sho <Short rtMe Mess ssag ageF eFil ilte ter r (msg (msg=^ =^he hell llo. o.*$)> <EvalPyFilter (pyCode= ..)> <D <Des esti tina nati tion onAd Addr drFi Filt lter er (d (dst st_a _add ddr= r=^8 ^851 5111 11$) $)> > <Dat <DateI eInt nter erva valF lFil ilte ter r (201 (20144-09 09-0 -01, 1,20 2014 14-0 -099-30 30)> )> <Tim <TimeI eInt nter erva valF lFil ilte ter r (08: (08:00 00:0 :00, 0,18 18:0 :00: 0:00 00)> )> <TransparentFilter> <TG (tag=21401)> <S <Sou ourc rceA eAdd ddrF rFil ilte ter r (s (src rc_a _add ddr= r=^2 ^20\ 0\d+ d+)> )>

It is possible to obtain more information of a specific filter by typing  filter -s <fid>: jcli : fil jcli filter ter -s Septem September ber201 2014 4 DateIntervalFilter: Left Lef t bor border der = 2014-0 2014-09-0 9-01 1 Right Rig ht border border = 2014-0 2014-09-3 9-30 0

More control commands: •  filter -r <fid>: Remove filter

External business logic In addition to predefined filters listed above ( Filter manager ), ), it is possible to extend filtering with external scripts written in Python using the   EvalPyFilter. Here’s a very simple example where an  EvalPyFilter is matching the connector  cid  of a message: First, write an external python script :

3.10. Management CLI Modules

69

 

Jasmin Documentation, Release 0.9.3-beta

# File @ /opt /opt/jasm /jasmin-s in-script cripts/ro s/routing uting/abc/abc-conn connector ector.py  .py  if   routable. routable.connector connector. .cid   ==   'abc': 'abc': result   =   True else: result   =   False

Second, create an EvalPyFilter with the python script : jcli jcli : filt filter er -a Addi Adding ng a new new Filt Filter er: : (ok: (ok: save save, , ko: ko: exit exit) ) > type Eval EvalPyFil PyFilter ter jasmin.routing.Filters.EvalPyFilt jasmin.routing.F ilters.EvalPyFilter er arguments: pyCode > pyCode /opt/jasmin-scri /opt/jasmin-scripts/routing/abc-c pts/routing/abc-connector.py onnector.py > fid SimpleThir SimpleThirdPart dParty y > ok Successful Succe ssfully ly added Filter Filter [Eva [EvalPyFi lPyFilter lter] ] with fid: fid:Simpl SimpleThi eThirdPar rdParty ty

This example will provide an  EvalPyFilter (SimpleThirdPart  (SimpleThirdParty) y) that will match any message coming from the connector with cid  = abc. Using EvalPyFilter is as simple as the shown example, when the python script is called it will get the following global variables set: •   routable: one of the   jasmin.r jasmin.routing.Routabl outing.Routables.Routable es.Routable inheriters ( Routable for more details) •   result: (default to  False) It will be read by Jasmin router at the end of the script execution to check if the filter is matching the message passed through the routable variable, matched=True / unmatched=False Note:   It is possible to check for any parameter of the SMPP PDU: TON, NPI, PROTOCOL_ID ... since it is provided through the routable object.

Note:   Using   EvalPyFilter  off  offers ers the possibility to call external webservice webservices, s, databases ... for powerfull routing or even for logging, rating & billing through external third party systems.

Hint:   More examples in the this FAQ’s AQ’s question:  Can you provide an example of how to use EvalPyFilter ?

3.10.9 HTTP Client Client connector connector manager The HTTP Client connector manager module is accessible through the  httpccm  command and is providing the following features: Table 3.37:  httpccm command line options

Command -l, –list -a, –add -r FID, –remo –remove= ve=FID FID -s FID, –sho –show=FID w=FID

Description List HTTP client connectors Add a new HTTP client connector Remo Remove ve HTTP HTTP client client conn connecto ectorr using using it’ it’ss CID Sho Show w HTTP clie client nt connector connector usin using g it’ it’ss CID

A HTTP Client connector is used in SMS-MO routing, it is called with the message parameters when it is returned by a matched MO Route ( Receiving SMS-MO for more details).

70

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

When adding a HTTP Client connector, the following parameters are required: •   cid: Connector id (must be unique) •   url: URL to be called with message parameters •   method: Calling method (GET or POST) Here’s an example of adding a new HTTP Client connector: jcli jcli : http httpcc ccm m -a Addi Adding ng a new new Http Httpcc cc: : (ok: (ok: save save, , ko: ko: exit exit) ) > url http://10.10.20.125/receive-sms/m http://10.10.20.125/receive-sms/mo.php o.php > meth method od GET GET > cid cid HTTP HTTP-0 -01 1 > ok Successful Succe ssfully ly added Httpcc Httpcc [Htt [HttpConn pConnecto ector] r] with cid:H cid:HTTPTTP-01 01

All the above parameters can be displayed after Connector creation: jcli : htt jcli httpcc pccm m -s HTTP-0 HTTP-01 1 HttpConnector: cid = HTTP-0 HTTP-01 1 baseurl = http://10.10.20.125/receive-sms/ http://10.10.20.125/receive-sms/mo.php mo.php meth method od = GET GET

Listing Connectors will show currently added Connectors with their CID, Type, Method and Url: jcli jcli : http httpcc ccm m -l #Httpcc id Type #HTTP-01 HttpConnector Total Tot al Httpcc Httpccs: s: 1

Method URL GET http://10.10.20.125/receive-sms/mo.php

managerr 3.10.10 Stats manage The Stats manager module is responsible for showing real time statistics, aggregated counters and values such as current bound connections of a User, number of http requests, number of sent messages through a Route, Filter, Connector ... Note:   All values are collected during Jasmin’ Jasmin’ss uptime and they are lost when Jasmin goes off, Stats manager shall be used for monitoring activities but not for advanced business reports.

The Stats manager module is accessible through the  stats command and is providing the following features: Table 3.38:  stats command line options

Comman Comm and d –user= –us er=UID UID –users –smppc=CI –smp pc=CID D –s –smp mppc pcss –s –smp mpps psap apii

Desc Descri ript ptio ion n Sho Show w user user sta stats ts using using it’s it’s UID Show all users stats Show smpp conne connector ctor stat statss using using it it’s ’s CID Sh Show ow al alll sm smpp pp conn connec ecto tors rs st stat atss Sh Show ow SMPP SMPP Se Serv rver er API API st stat atss

The Stats manager covers different different sections, this includes Users, SMPP Client connectors, Routes (MO and MT), APIs (HTTP and SMPP).

3.10. Management CLI Modules

71

 

Jasmin Documentation, Release 0.9.3-beta

User statistics The Stats manager exposes an overall view of all existent users as well as a per-user information view: •  stats –users: Will show an overall view of all existent users •  stats –user foo: Will show detailed information for  foo Here’s an example of showing an overall view where users  sandra and  foo  are actually having 2 and 6 SMPP bound connections, user  bar  is using the HTTP Api only and  sandra is using both APIs: jcli : sta jcli stats ts --user --users s #User id SMPP Bound connections #sandra 2 #foo 6 #bar 0 Total Tot al users: users: 3

SMPP L.A. 2019-06-02 15:35:01 2019-06-02 15:35:10 ND

HTTP requests counter 20 0 1289

HTTP L.A. 2019-06-01 12:12:33 ND 2019-06-02 15:39:12

The columns shown for each user are explained in the following table: Table 3.39: Columns of the overall statistics for users users

Column SMPP Bound Bound cconnec onnection tionss SMPP L.A.

Description Numbe Numberr of curren currentt bound bound SMPP conn connecti ections ons SMPP Server Last Activity date & time

HTTP rrequ HTTP equest estss coun counter ter HTTP L.A.

Counte Counterr o off all htt http p requ request estss d done one by the use userr HTTP Api Last Activity date & time

Here’s an example of showing  sandra‘s detailed statistics: jcli : sta jcli stats ts --user --user sandra sandra #Item Type #bind_count SMPP #submit_sm_count SMPP #submi #su bmit_s t_sm_r m_requ equest est_co _count unt SMP SMPP P #unbind_count SMPP #data_sm_count SMPP #las #last t_ac _activ tivity_ ity_a at SMPP MPP #other #ot her_su _submi bmit_e t_erro rror_c r_coun ount t SMP SMPP P #thr #throt ottl tlin ing_ g_er erro ror_ r_co coun unt t SMPP SMPP #bound_con #boun d_connect nections_ ions_count count SMPP #elink_count SMPP #qos #qos_l _las ast_ t_su subm bmit it_s _sm_ m_at at SMPP SMPP #deliver_sm_count SMPP #connects_count HTTP #last_activity_at HTTP #rate_request_count HTTP #s #sub ubmi mit_ t_sm sm_r _req eque uest st_c _cou ount nt HT HTTP TP #q #qos os_l _las ast_ t_su subm bmit it_s _sm_ m_at at HT HTTP TP #balance_request_count HTTP

Server Server Ser Server ver Server Server Serv erver Server Server Serv Server er S Server erver Server Serv Server er Server Api Api Api Ap Api i Ap Api i Api

Value 26 1500 150 1506 6 24 0 2019 2019-0 -06 6-02 -02 15:3 15:35 5:01 :01 4 2 {'bi {'bind_tr nd_transm ansmitter itter': ': 1, ' 'bind_ bind_recei receiver' ver': : 1, 'bi 'bind_tr nd_transce ansceive ive 16 2019 2019-0 -066-02 02 12:3 12:31: 1:23 23 1430 156 2019-06-01 12:12:33 20 10 102 2 20 2019 19-0 -055-22 22 15 15:5 :56: 6:02 02 16

This is clearly a more detailed view for user  sandra, the following table explains the items shown for  sandra:

72

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.40: Details user statistics view view items

Item last last_a _act ctiivi vity ty_a _att bind_count bound_con bound _connecti nections_c ons_count ount submit_s subm it_sm_re m_request quest_coun _countt

Type SM SMPP PP Se Serv rver er SMPP Server SMPP Serv Server er SMPP Serv Server er

Description Da Date te & ti time me of la last st rece receiived PD PDU U fr from om user user Binds counter value Curr Currentl ently y bound connectio connections ns Numb Number er of requ requested ested Subm SubmitSM itSM (MT mess messages) ages)

subm submit it_s _sm_ m_co coun untt thr thrott ottlin ling_e g_erro rror_c r_coun ountt other_sub othe r_submit_ mit_erro error_cou r_count nt eli elink nk_c _cou oun nt del deliv iver_ er_sm sm_co _count unt da data ta_s _sm_ m_co coun untt qos_la qos _last_ st_sub submit mit_sm _sm_at _at unbind_count qos_la qos _last_ st_sub submit mit_sm _sm_at _at connects_count last_activity_at submit sub mit_sm _sm_re _reque quest_ st_cou count nt rate rate_r _req equ ues est_ t_ccou oun nt ba bala lanc nce_ e_re requ ques est_ t_co coun untt

SMPP SMPP Se Serv rver er SMPP SMPP Ser Serve verr SMPP Serv Server er SM SMPP PP Serv Server er SMP SMPP P Ser Serve verr SMPP SMPP Serv Server er SMPP SMPP Ser Serve verr SMPP Server HTTP HTTP Api HTTP Api HTTP Api HTT HTTP P Api HT HTTP TP Ap Apii HTTP HTTP Api Api

Nu Numb mber er of Subm Submit itSM SM (MT (MT mess messag ages es))  really sent by user Thr Thrott ottlin ling g err errors ors rec recei eive ved d by use userr Any other error received received in response response of S Submi ubmitSM tSM requests requests Num Numbe berr of enqu enquiire_l re_lin ink k PD PDUs Us sent sent by user ser Num Number ber of Deliv DeliverS erSM M (MO (MO messa messages ges or receip receipts) ts) recei receive ved d Numb Number er of Da Data taSM SM (M (MO O me mess ssag ages es or rece receip ipts ts)) rece receiived ved Dat Datee & tim timee of last last Submi SubmitSM tSM (MT Mes Messag sage) e) sent sent Unbinds counter value Date Date & tim timee of last last Submi SubmitSM tSM (MT Mes Messag sagee sent) sent) HTTP request counter value Date & time of last HTTP request Number Number of Submit SubmitSM SM (M (MT T messa messages ges)) sent sent Num Numbe berr of rat atee requ requeests sts Numb Number er of ba bala lanc ncee requ reques ests ts

SMPP Client connectors statistics The Stats manager exposes an overall view of all existent smppc connectors as well as a per-smppc information view: •  stats –smppcs: Will show an overall view of all existent smppc connectors •  stats –smppc foo: Will show detailed information for  foo Here’s an example of showing an overall view where smppc connectors  MTN  and  ORANGE  are actives, connector SFONE made no activity at all: jcli : sta jcli stats ts --smpp --smppcs cs #Connector id Connected at #MTN 6 #Orange 1 #SFONE 0 Total connectors: connectors: 3

Bound at 2019-06-02 15:35:01 2019-06-02 15:35:01 ND

Disconnected at 2019-06-02 15:35:01 2019-06-02 15:35:01 ND

Submits 12/10 0/0 0/0

The columns shown for each user are explained in the following table: Table 3.41: Columns of the overall statistics for smppcs smppcs

Column Bo Boun und d coun countt Connec Con nected ted at Boun Bound d at Disconnect Disco nnected ed at at Su Subm bmit itss De Deli liv vers ers QoS err errss Othe Otherr er errs rs

Description Bi Bind ndss coun counte terr va valu luee Last Last con connec nectio tion n dat datee & time time Last Last succ succes essf sful ul bind bind date date & ti time me Last disc disconnec onnection tion date & time time Nu Numb mber er of re requ ques este ted d Su Subm bmit itSM SM PD PDUs Us /  Sent  Sent SubmitSM PDUs Nu Numb mber er of re rece ceiived ved Deli Delive verS rSM M PD PDUs Us /  Number  Number of received DataSM PDUs Number Number of rej reject ected ed Submit SubmitSM SM PDU PDUss due to thr thrott ottlin ling g limita limitatio tion n Numb Number er of al alll ot othe herr re reje ject ctio ions ns of Su Subm bmit itSM SM PD PDUs Us

Here’s an example of showing  MTN‘s detailed statistics:

Delivers 9 /10 9/ 12022/0 0/0

QoS errs 2 0 0

Other 0 0 0

3.10. Management CLI Modules

73

 

Jasmin Documentation, Release 0.9.3-beta

jcli jcli : stat stats s --sm --smpp ppc c MTN MTN #Item #bound_at #disconnected_count #other_sub #othe r_submit_ mit_error error_coun _count t #submit_sm_count #created_at #bound_count #last_ #la st_rec receiv eived_ ed_eli elink_ nk_at at #elink_count #thr #throt ottl tlin ing_ g_er erro ror_ r_co coun unt t #l #las ast_ t_se sent nt_e _eli link nk_a _at t #connected_count #connected_at #deliver_sm_count #data_sm_count #submi #su bmit_s t_sm_r m_requ equest est_co _count unt #last_seqNum #last_seqNum_at #last_sent_pdu_at #disconnected_at #las #last_ t_re rece ceiv ived ed_p _pdu du_a _at t #interceptor_count #inter #in tercep ceptor tor_er _error ror_co _count unt

Value 2019-06-02 2 0 2300 2019-06-01 3 201 2019-0 9-06-0 6-02 2 34 44 20 2019 19-0 -066-02 02 3 2019-06-02 1302 0 234 2344 4 1733 2019-06-02 2019-06-02 2019-06-01 2019 2019-0 -066-02 02 0 0

15:35:01

12:29:42 15: 15:32: 32:28 28

15 15:3 :34: 4:57 57 15:35:01

15:35:57 15:35:59 10:18:21 15:3 15:36: 6:01 01

This is clearly a more detailed view for connector  MTN, the following table explains the items shown for  MTN: Table 3.42: Details of smppc statistics statistics view items

Item created_at last_r last_rece eceiv ived_ ed_pdu pdu_at _at las astt_s _sen entt_p _pdu du_a _att last_rec last _receiv eived_el ed_elink_a ink_att last last_s _sen ent_ t_el elin ink_ k_at at last last_s _seq eqNu Num_ m_at at las astt_s _seq eqNu Num m connected_at bound_at disc discon onn nec ectted ed_a _att co conn nneected cted_ _cou count bound_count disc discon onne nect cted ed_c _cou ount nt submit_sm_request_count submit_sm_re quest_count subm submit it_s _sm_ m_co coun untt thr thrott ottlin ling_e g_erro rror_c r_coun ountt other_submit_error_count other_submit_ error_count elink_count del deliv iver_ er_sm sm_co _count unt da data ta_s _sm_ m_co coun untt in inte terc rcep epto tor_ r_co coun untt intercept inte rceptor_e or_error rror_coun _countt

Description Connector creation date & time Dat Datee & tim timee of last last rec recei eive ved d PDU Dat Date & ti tim me of las astt sent sent PD PDU U Date & time of last rece receive ived d enquire_l enquire_link ink PDU Date Date & ti time me of la last st se sent nt enqu enquir ire_ e_li link nk PD PDU U Da Date te & ti time me of la last st se sequ quen ence ce_n _num umbe berr clai claim m Valu luee of las astt cl clai aim med se sequ queenc ncee_n _nu umbe berr Last connection date & time Last successful bind date & time La Last st dis isco con nne neccti tion on da date te & tim imee La Last st con onn nect ection da datte & ti tim me Binds counter value Last Last di disc scon onne nect ctio ion n da date te & ti time me Number of requested SubmitSM (MT messages) Nu Numb mber er of Su Subm bmit itSM SM (MT (MT me mess ssag ages es))  really  sent (having  ESME_ROK  response) Thrott Throttlin ling g err errors ors rec recei eived ved Any other error received received in in re response sponse of SubmitSM requests Number of enquire_link PDUs sent Num Number ber of Del Deliv iverS erSM M (MO messag messages es or receip receipts) ts) rec recei eive ved d Numb Number er of Data DataSM SM (M (MO O me mess ssag ages es or rece receip ipts ts)) rece receiv ived ed Numb Number er of succ succes essf sful ully ly in inte terc rcep epte ted d me mess ssag ages es (M (MO) O) Numb Number er of fail failures ures when inte intercep rcepting ting mess messages ages (MO)

74

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

SMPP Server API statistics The Stats manager exposes collected statistics in SMPP Server API through the following  jCli  command: •  stats –smppsapi Here’s an example of showing the statistics: jcli : sta jcli stats ts --smpp --smppsap sapi i #Item #disconnect_count #bound_rx_count #bound_tx_count #other_sub #othe r_submit_ mit_error error_coun _count t #bind_rx_count #bind_trx_count #created_at #las #last_ t_re rece ceiv ived ed_e _eli link nk_a _at t #elink_count #thr #throt ottl tlin ing_ g_er erro ror_ r_co coun unt t #submit_sm_count #connected_count #connect_count #bound_trx_count #data_sm_count #submi #su bmit_s t_sm_r m_requ equest est_co _count unt #deliver_sm_count #last_sent_pdu_at #unbind_count #las #last_ t_re rece ceiv ived ed_p _pdu du_a _at t #bind_tx_count #interceptor_count #inter #in tercep ceptor tor_er _error ror_co _count unt

Value 2 1 0 0 0 0 2019-06-04 02:22:17 ND 89 1 199 2 16 1 2 200 145 2019-06-05 12:12:13 6 2019 2019-0 -066-05 05 12:1 12:16: 6:21 21 6 0 0

The following table explains the items shown in the above example:

3.10. Management CLI Modules

75

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.43: Details of smppsapi statistics view view items

Item created_at last_r last_rece eceiv ived_ ed_pdu pdu_at _at las astt_s _sen entt_p _pdu du_a _att last_rec last _receiv eived_el ed_elink_a ink_att

Description Connector creation date & time Dat Datee & tim timee of last last rec recei eive ved d PDU Dat Date & ti tim me of las astt sent sent PD PDU U Date & time of last rece receive ived d enquire_l enquire_link ink PDU

co conn nneected cted_ _cou count connect_count disc discon onn nec ectt_c _cou ount nt bind bind_ _tr trx_ x_ccou oun nt bo boun und_ d_tr trx_ x_co coun untt bind_rx_count bo boun und_ d_rx rx_c _cou ount nt bind bind_ _tx tx_c _co oun untt bo boun und_ d_tx tx_c _cou ount nt submit_sm_request_count submit_sm_re quest_count subm submit it_s _sm_ m_co coun untt de deli live ver_ r_sm sm_c _cou ount nt data data_s _sm_ m_co coun untt elink_count

La Last st con onn nect ection da datte & ti tim me TCP Connection request count Disc Discon onne nect ctio ion n co cou unt Tra rans nsccei eiv ver bi bind nd re requ queest cou oun nt Actu Actual ally ly boun bound d tr tran ansc scei eive verr co conn nnec ecti tion onss coun countt Receiver bind request count Actu Actual ally ly bo boun und d re rece ceiv iver er co conn nnec ecti tion onss coun countt Tra rans nsm mitte terr bi bind nd re requ queest cou oun nt Actu Actual ally ly bo boun und d tr tran ansm smit itte terr conn connec ecti tion onss coun countt Number of requested SubmitSM (MT messages) Numb Number er of Subm Submit itSM SM (M (MT T me mess ssag ages es)) acce accept pted ed (ret (retur urne ned d a  ESME_ROK  response) Numb Number er of Deli Delive verS rSM M (M (MO O me mess ssag ages es or rece receip ipts ts)) sent sent Nu Numb mber er of Da Data taSM SM (MO (MO me mess ssag ages es or rece receip ipts ts)) sent sent Number of enquire_link PDUs received

thr thrott ottlin ling_e g_erro rror_c r_coun ountt other_submit_error_count other_submit_error_count in inte terc rcep epto tor_ r_co coun untt intercept inte rceptor_e or_error rror_coun _countt

Thrott Throttlin ling g err errors ors ret return urned ed Any other error returned in response of SubmitSM requests Numb Number er of succ succes essf sful ully ly in inte terc rcep epte ted d me mess ssag ages es (M (MT) T) Numb Number er of fail failures ures when inte intercep rcepting ting mess messages ages (MT)

statistics ics HTTP API statist The Stats manager exposes collected statistics in HTTP API through the following  jCli  command: •  stats –httpapi Here’s an example of showing the statistics: jcli : sta jcli stats ts --http --httpapi api #Item #ser #serv ver_ er_err error_c or_co ount unt #last_request_at #throughpu #thro ughput_er t_error_c ror_count ount #success_count #route_error_count #request_count #auth_error_count #created_at #las #last t_su _succe ccess_a ss_at t #cha #charg rgin ing_ g_er erro ror_ r_co coun unt t #interceptor_count #inter #in tercep ceptor tor_er _error ror_co _count unt

Value 120 120 ND 4 14332 156 20126 78 2019-06-04 02:22:17 201 2019-06 9-06-05 18: 18:20: 20:29 178 178 0 0

The following table explains the items shown in the above example:

76

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Table 3.44: Details of httpapi statistics view items items

Item created_at last last_r _req eque uest st_a _att last_s last_succ uccess ess_at _at request_count

Description Connector creation date & time Da Date te & ti time me of la last st ht http tp re requ ques estt Dat Datee & tim timee of last last succes successfu sfull htt http p reques requestt (SMS (SMS is accept accepted ed for sendin sending) g) HTTP request count

succ succes ess_ s_co coun untt auth auth_e _err rror or_c _cou ount nt ro rout ute_ e_er erro ror_ r_co coun untt throughpu thro ughput_er t_error_ ror_count count charging_ char ging_error error_coun _countt serve server_e r_erro rror_c r_coun ountt int interc ercept eptor_ or_cou count nt interceptor_error_count interceptor_e rror_count

Succ Succes essf sful ul HT HTTP TP re requ ques estt coun countt (SMS (SMS is acce accept pted ed fo forr send sendin ing) g) Auth Authen enti tica cati tion on er erro rors rs coun countt Ro Rout utee no nott fo foun und d er erro rors rs coun countt Throughput Throughput exceeded exceeded errors errors count count Char Charging ging/Bill /Billing ing erro errors rs coun countt Unkno Unknown wn serve serverr err errors ors cou count nt Number Number of succes successfu sfully lly int interc ercept epted ed messa messages ges (MT) (MT) Number of failures when intercepting messages (MT)

3.1 3.11 1 Bill Billing ing Jasmin  comes with a user billing feature that lets you apply rates on message routes, every time a user sends a SMS Jasmin comes through a rated route he’ll get charged, once he runs out of credit no more sending will be permitted.  are not rated by default, you must  define the rate of each Important:   New routes cr created eated through MT router manager  are route in order to enable billing.

(SMPP Server and HTTP API) the same way. way. Note:   Billing is applied on all channels (SMPP

3.11.1 Billing quotas A user can be charged charged through through 2 type typess of quotas (balan (balance ce and/or sms_count), sms_count), if he reaches the limit of one of thes thesee quotas no more sending will be permitted, no matter the used channel (SMPP Server or HTTP API).

1. Balance quota The route rate will be charged on the user balance, let’s get into these use cases for better comprehension: • When sending one SMS through through a route rat rated ed 1.2, user’s balance will get decreased by  1.2 • When sending fi five ve SMS through a rou route te rated 0.2, user’s balance will get decreased by  1  will have unlimited balance by default, assuming you’ll apply Important:   New users crea created ted through User manager  will  in order to enable billing. postpaid billing (or no billing at all ), user’s balance must be  defined  in

Rate unit

You can see that the rates have no  unit  or  or  currency, this will offer better flexibility for different business cases, you can consider the rates as:

3.11. Billing

77

 

Jasmin Documentation, Release 0.9.3-beta

• Local Jasmin currency and keep a rate for converting to real-lif real-lifee currency currency.. • Real-life currency • etc .. In all cases, Jasmin will never manage the rate  unit  (or  (or  currency), all it does is to ensure users are correctly charged by the rates you define. Asynchron Asynchronous ous billing

As explained  later , it is important to know that whatever the used protocol, SMS is always sent  asynchronously, this means there’s always an acknowledgment to be received for every sent SMS; Jasmin provides an  optional  adapted billing algorithm which is able to charge the user   asynchronousl asynchronously y: 1. A defined percentage of the route rate is charged charged when the user submits the SMS for sending. 2. The rest is charged when the SMS is acknowledged by the next relay, relay, in SMPP protocol, this means receiving SUBMIT_SM_RESP  PDU, more details  here. Asynch Asy nchron ronous ous billin billing g is aut automa omatic ticall ally y enable enabled d when when the user user ha have ve  early_decrement_balance_percent   de fined    (unde (undefin fined ed by de defa faul ult) t),, le let’ t’ss ge gett ba back ck to exam exampl ples es fo forr bett better er comp compre rehe hens nsio ion, n, assu assumi ming ng user user have have early_decrement_balance_per early_decrem ent_balance_percent cent = 25: • When sending one SMS through through a route rat rated ed 1.2: • When sending, user’ user’ss balance is decreased decreased by 0.3  ( 1.2 x  25%) • When acknowledg acknowledged, ed, user’s balance balance is decreased by 0.9  (the rest) • When sending sending five  SMS through a route rated  0.2: • When sending, user’ user’ss balance is decreased decreased by 0.25 ( 5 x  0.2  x  25%) • For each acknowle acknowledged dged SMS, user’s balance balance is decreased by 0.15 • When all five  sent messages are acknowledged, the final charged amount is  0.75 (the rest) Using asynchronous billing can be helpful in many use cases: • Charge only when tthe he SMS is acknowledged acknowledged • If SMS is not acknowledged for some reason, user can not fill Jasmin’s Jasmin’s queues by SMS requests indefinitely indefinitely,, he’ll get out of credits • etc ..

sms_count ount quota 2. sms_c Simpler than  Balance  management,  sms_count  is  is a counter to be decreased whenever the user submits the SMS for sending, let’s get into these use cases for better comprehension: • When sending one SMS tthrough hrough a route, user’ user’ss  sms_count  will  will get decreased by  1 • When sending fi five ve SMS through a rou route, te, user’s user’s  sms_count  will  will get decreased by  5 Note:   When defined,  sms_count  is  is always decreased no matter the route is rated or not.

78

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

through rough  User manager  will have unlimited sms_count by default, assuming you’ll Important:   New users created th  in order to enable billing (or limit). apply postpaid billing (or no billing at all ), user’s  sms_count  must  must be defined  in

3.11.2 Proc Process ess flow flow The following process flow shows how billing is done through HTTP Api (same process is applied on SMPP Server), it is including all types of billing: • bala balance nce quo quota ta billing billing (ref ) including asynchronous billing (ref ) • sms_count quota billing billing (ref )

Fig. 3.10: Billing process flow

3.11. Billing

79

 

Jasmin Documentation, Release 0.9.3-beta

Asynchronous billing call flow When enabled,  Asynchronous billing  algorithm can charge user every time an acknowledgment is received for each SMS he sent earlier, the following call flow explain the asynchronous billing algorithm:

Fig. 3.11: Asynchronous billing call flo flow w In the above figure, user is charged early before submitting SMS to SMSC, and the charged later when the SMSC acknowledge back reception of the message, as detailed  earlier ,   the charged amount in early stage is defined by early_decrement_balance_percent set in user profile. Note:   The route rate is expressed on a per-SUBMIT_SM basis, submitting a long SMS will be splitted into multiple submit_sm SMPP PDUs, each one will be charged on user.

The below figure explain how asynchronous billing is handling long content messages, assuming a user is submitting a message containing 400 characters, which will imply sending 3 submit_sm SMPP PDUs: Asynchronous billing is mainly relying on AMQP broker (like messaging (like  messaging)), The AMQP broker is providing a queuing mechanism, through the following illustration you can see how asynchronous billing is done: When receiving a   SUBMIT_SM_RESP  PDU,   submit_sm_resp_event()  method is called ( called  ( more details here), it will

80

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.12: Asynchronous billing call flo flow w for long content messages messages

3.11. Billing

81

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.13: Asynchronous bill billing ing AMQP m message essage exchange exchange

82

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

check if there’s a remaining bill to charge on user and publish it on   bill_request.submit_sm_resp.UID (using billing exchange) where UID is the concerned User ID. RouterPB’s   bill_request_submit_sm_resp_callback()  is listening on the same topic and it will be fired whenever it consumes a new bill request, as the Router is holding User objects in memory, it will simply update their balances with the bill amount. Jasmin is doing everything in-memory for performance reasons, including User charging where the balance must be persisted to disk for later synchronization whenever Jasmin is restarted, this is why RouterPB is automatically persisting Users and Groups to disk every   persistence_timer_secs persistence_timer_secs seconds as defined in jasmin.cfg file (INI format, located in /etc/jasmin). /etc/jasmin). Important:   Set   persistence_timer_secs persistence_timer_secs  to a reasonable value, keep in mind that every disk-access operation will cost you few performance points, and don’t set it too high as you can loose Users balance data updates.

3.12 Messa Messaging ging flows Messaging is heavily relying on an AMQP broker using topics to queue messages for routing, delivering and acking back. The AMQP broker is providing a strong store & forward queuing mechanism, through the following illustration you can see how every messaging component is asynchronously connected to the broker. Five main actors are messaging through the “ messaging” topic, their business logic are explained in the below paragraphs.

3.12.1 SMPPC SMPPClientMan lientManagerPB agerPB This is a PerspectiveBroker  (PB)  (PB) responsible of managing SMPP Client connectors (list, add, remove, start, stop, send SMS, etc ...), we’ll be only covering the latter (Send SMS). When the   perspective_submit_sm() perspective_submit_sm() is called with a SubmitSm PDU and destination connector ID, it will build an AMQP Content message and publish it to a queue named submit.sm.CID where CID  is the destination connector ID.

Note: perspectiv perspective_submit_sm() e_submit_sm()  is called to. from HTTP API and SMPP Server API after they check with RouterPB for the right connector to send a SubmitSM

Every SMPP Connector have a consumer waiting for these messages, once published as explained above, it will be consumed by the destination connector’s submit_sm_callback() submit_sm_callback() method (c.f.   SMPPClientSML SMPPClientSMListener  istener ).

3.12.2 Router RouterPB PB This is another  PerspectiveBroker   (PB) responsible of routing DeliverSm messages, these are received through the SMPP client connector’s   deliver_sm_event_interceptor()  method (c.f.  SMPPClientSMListener ) which publish to  deliver.sm.CID, the RouterPB main role is to decide whether to route DeliverSm messages to: •   deliver_sm_thrower.smpps: if the message is to be delivered through SMPP Server API. •   deliver_sm_thrower.http: if the message is to be delivered through a HTTP connector.

3.12. Messaging flows

83

 

Jasmin Documentation, Release 0.9.3-beta

Fig. 3.14: AMQP Mes Messagi saging ng flows

84

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

3.12.3 SMPPC SMPPClientSML lientSMListener istener Every SMPP Client connector have one attached  SMPPClientSMLis SMPPClientSMListener  tener  instance,  instance, it is responsible for handling messages exchanged through the SMPP Client connector using the following event catchers:

deliver_sm_event_interceptor Every received DeliverSm PDU is published directly to the broker with the following assumptions: • If it’ it’ss a SMS-MO message it will get published as an AMQP Content mes message sage to   deliver_sm.CID  where  CID is the source connector ID, this message will be handled by the  RouterPB. • If it’s a deliv delivery ery receipt and if it were requested when sending the SubmitSm, it will get published as an AMQP Content message to  dlr_thrower.http  or  dlr_thrower.smpps  (depends on the used channel for sending initial SubmitSM) for later delivery by DLRThrower’ DLRThrower’ss   dlr_throw dlr_throwing_callback() ing_callback() method. Note: deliver_sm deliver_sm_event_int _event_interceptor() erceptor() will check for interception rules before proceding to routing, c.f. Interception c.f.  Interception for more details.

submit_sm_callback It is a simple consumer of  submit.sm.CID   submit.sm.CID where  CID is its connector ID, it will send every message received through SMPP connection.

submit_sm_resp_event It is called for every received SubmitSmResp SubmitSmResp PDU, will check if the related SubmitSm was requiring a delive delivery ry receipt and will publish it (or not) to  dlr_thrower.http or dlr_thrower.smpps (depends on the used channel for sending initial SubmitSM). Note:   There’s There’s no actual reason why messages are published to  submit.sm.resp.CID, this may change in future.

deliverSmThr SmThrower ower 3.12.4 deliver This is will through any received message from  deliver_sm_thrower.http  to its final http connector, c.f.   Receiving SMS-MO  for details and from deliver_sm_thrower.smpps  to its final SMPP Server binding.

3.12.5 DLR DLRThro Thrower wer This is will through any received delivery receipt from  dlr_thrower.http  to its final http connector, c.f.   Receiving  DLR for details and from  dlr_thrower.smpps  to its final SMPP Server binding.

3.12. Messaging flows

85

 

Jasmin Documentation, Release 0.9.3-beta

3.13 User FAQ FAQ 3.13.1 Could not find a version version that satisfies the requirement requirement jasmin Installing Jasmin using pip  will through this error: $ sud sudo o pip instal install l pyt python hon-ja -jasmi smin n [sudo] [sudo ] pass password word for richa richard: rd: Downloading/unpacking Downloading/unpa cking jasmin Could Cou ld not find find a ver versio sion n tha that t sat satisf isfies ies the req requir uireme ement nt jas jasmin min (fr (from om ver versio sions: ns: 0.6 0.6b1, b1, 0.6 0.6b10 b10, , 0. Cleaning Clean ing up... up... No dis distri tribut bution ions s mat matchi ching ng the ver versio sion n for jas jasmin min Storing Stori ng debug log for failu failure re in /home /home/ric /richard/ hard/.pip/ .pip/pip. pip.log log

This is common question, since Jasmin is still tagged as a ‘Beta’ version, pip installation must be done with the  –pre parameter: $ sud sudo o pip instal install l --p --pre re pyt python hon-ja -jasmi smin n ...

Hint:   This is clearly documented documented in Installation installation steps.

Cannott connect to telnet console console after starting Jasmin 3.13.2 Canno According to the installation guide, Jasmin requires running RabbitMQ and Redis servers, when starting it will wait for these servers to go up. If you already have these requirements, please check jcli and redis-client logs: • /var/lo /var/log/jasmin/redi g/jasmin/redis-client.log s-client.log • /var/lo /var/log/jasmin/jcl g/jasmin/jcli.log i.log Hint:   Please check  Prerequisites  Prerequisites & Dependencies before installing.

3.13.3 Should 3.13.3 Should i exp expose ose my SMPP Server Server & HTTP API to the pub public lic internet internet for remote users ? As a security best practice, place  Jasmin instance(s) behind a firewall and apply whitelisting rules to only accept users you already know, a better solution is to get VPN tunnels with your users. If for some reasons you cannot consider these practices, here’s a simple iptables configuration that can help to prevent Denial-of-service Denial-of-ser vice attacks: iptables iptabl es iptables iptab les iptabl ipt ables es iptabl ipt ables es iptabl ipt ables es

-I -N -I -A -A

INPUT INPUT -p tcp RULE_SMPP RULE_SMPP INPUT INPUT -p tcp RULE_S RULE_SMPP MPP -j RULE_S RULE_SMPP MPP -j

--dport --dport 277 2775 5 -m sta state te --s --stat tate e NEW -m rec recent ent --s --set et --n --name ame SMP SMPP_C P_CONN ONNECT ECT --dport --dport 277 2775 5 -m sta state te --s --stat tate e NEW -m rec recent ent --u --upda pdate te --s --seco econds nds 60 --h --hitc itcoun oun LOG --l --logog-pre prefix fix 'DR 'DROPP OPPED ED SMP SMPP P CON CONNEC NECT T ' --l --logog-lev level el 7 DRO DROP P

This will drop any SMPP Connection request coming from the same source IP with more than 3 times per minute ...

86

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

3.13.4 Does Jasmin persist persist its configuration configuration to disk ? Since everything in Jasmin runs fully in-memory, what will happen if i restart Jasmin or if it crashes for some reason ? how can i ensure my configuration (Connectors, Users, Routes, Filters ...) will be reloaded with the same state they were in before Jasmin goes off ? Jasmin is doing everything everything in-memory for performance reasons, and is automatically automatically persisting newly updated configurations every  persistence_timer_secs persistence_timer_secs seconds as defined in jasmin.cfg file. Important:   Set   persistence_timer_secs persistence_timer_secs  to a reasonable value, keep in mind that every disk-access operation will cost you few performance points, and don’t set it too high as you can loose critical updates such as User balance updates.

3.13.5 When receiving receiving a DLR: Got a DLR for an unknown message message id The following error may appear in  messages.log while receiving a receipt (DLR): WARN WARNIN ING G

4403 4403 Got a DLR DLR for for an unknow unknown n mess messag age e id: id: 7888 788821 21

This issue can be caused by one of these: • The receipt is recei received ved and it indicates a message id that did not get sent by Jasmin, Jasmin, • The receipt is receive received d for a message sent by Jasmin, but message id is not recognize, if it’s the case then find below what you can do. What’s happening:

When sending a message ( submit_sm) the upstream connector will reply back with a first receipt ( submit_sm_resp ) where it indicates the message id for further tracking, then it will send back another receipt ( deliver_sm  or  data_sm) with the same message it and different delivery delivery state. The problem occurs when the upstream connector returns the same message id but in different encodings. Solution:

Use the  dlr_msgid  parameter as shown in  SMPP Client connector manager  to   to indicate the encoding strategy of the upstream partner/connector.

3.14 Developer FAQ 3.14.1 How to ‘log’ messages messages in a third party party database database ? Jasmin runs without a database, everything is in-memory and messages are exchanged through AMQP broker (RabbitMQ), if you need to get these messages you have to consume from the right queues as described in  Messaging flows.. flows Here’ss an example: Here’ contribution: Thanks to Pedro to Pedro‘‘s contribution: Here Here is the the PySQ PySQLP LPoo ool l mod mod to @far @farir irat at ´s gist gist https://gist.github.com/pguillem/ https://gist.git hub.com/pguillem/5750e8db352f00113 5750e8db352f001138f2 8f2 Here Here is the the code code to laun launch ch the the cons consum umer er as a syst system em Daem Daemon on in Debi Debian an/U /Ubu bunt ntu u https://gist.github.com/pguillem/ https://gist.git hub.com/pguillem/19693defb3feb0c02 19693defb3feb0c02fe7 fe7

3.14. Developer FAQ

87

 

Jasmin Documentation, Release 0.9.3-beta

1) 2) 3) 4)

creat create e jasm jasmind_c ind_consum onsumer er file in /etc /etc/init /init.d/ .d/ chmo chmod d a+x a+x Mod Modify ify the path and scr script ipt name of you your r con consum sumer er in jas jasmin mind_c d_cons onsume umer r Rem Rememb ember er to exec exec "up "updat date-r e-rc.d c.d jas jasmin mind_c d_cons onsume umer r def defaul aults" ts" in ord order er to sta start rt at boo boot t

Cheers Pedro

 More on this: # Gist from https://gist.git https://gist.github.com/farirat/ hub.com/farirat/5701d71bf6e404d17 5701d71bf6e404d17cb4 cb4

import   cPickle   as   pickle from    twisted.internet.defer   import   inlineCallbacks from  from   from   twisted.internet   import   reactor from  from  twisted.internet.protocol  twisted.internet.protocol   import   ClientCreator from  from    twisted.python   import   log from   txamqp.protocol   import   AMQClient from   from   from   txamqp.client   import   TwistedDelegate import   txamqp.spec @inlineCallbacks gotConnection(conn, , user username, name, passw password): ord): def   gotConnection(conn  print   "Connecte "Connected d to brok broker." er." yield   conn. conn.authenticate(us authenticate(username, ername, password) "Authenticated cated. . Read Ready y to rece receive ive mess messages" ages"  print   "Authenti chan   =   yield    conn. conn.channel( channel(1 1) chan.channel_open() yield   chan.

yield   chan. chan.queue_declare(queue queue_declare(queue= ="someQueueName" "someQueueName") ) # Bin Bind d to sub submit mit.sm .sm. .*   and submit.sm.resp.*   routes yield   chan. chan.queue_bind(queue queue_bind(queue= ="someQueueName" "someQueueName", , exch exchange ange= ="messaging" "messaging", , routi routing_ke ng_key y='submit.sm.*') yield   chan. chan.queue_bind(queue queue_bind(queue= ="someQueueName" "someQueueName", , exch exchange ange= ="messaging" "messaging", , routi routing_ke ng_key y='submit.sm.resp.*

yield   chan. chan.basic_consume(queue basic_consume(queue= ='someQueueName' 'someQueueName', , no_ no_ack ack= =True True, , consu consumer_t mer_tag ag= ="someTag" "someTag") ) conn.queue( queue("someTag" "someTag") ) queue   =   yield    conn. # Wai Wait t for mes messag sages es # Th This is ca can n be do done ne th thro roug ugh h a ca call llba back ck .. ... . while   True: True: queue.get() msg   =   yield    queue. props   =   msg. msg.content content. .properties pdu   =   pickle. pickle.loads(msg loads(msg. .content content. .body)

if   msg. msg.routing_key[: routing_key[:15 15] ]   ==   'submit.sm.resp.': 'submit.sm.resp.': 'SubmitSMResp: status:   %s %s, , msg msgid: id:   %s %s' '   %   (pdu. (pdu.status,  print   'SubmitSMResp: props['message-id']) props['message-id' ]) msg.routing_key[: routing_key[:10 10] ]   ==   'submit.sm.': 'submit.sm.': elif   msg.  print   'SubmitSM: 'SubmitSM: from   %s   to   %s %s, , con conten tent: t:   %s %s, , msg msgid: id:   %s %s' '   %   (pdu. (pdu.params[ params['source_addr' 'source_addr'] ] pdu. pdu .params[ params['destination_addr' 'destination_addr'], ], pdu.params[ pdu. params['short_message' 'short_message'], ], props['message-id' props[ 'message-id']) ])

else:

 print   'unknown 'unknown rout route' e'

88

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

# A clea clean n wa way y to te tear ar do down wn an and d st stop op yield   chan. chan.basic_cancel( basic_cancel("someTag" "someTag") ) yield   chan. chan.channel_close() conn.channel( channel(0 0) chan0   =   yield    conn. yield   chan0. chan0.connection_close() reactor.stop() reactor.

if   __name__   __name__   ==   "__main__": "__main__": """ This Thi s exa exampl mple e wil will l con connec nect t to Rab Rabbit bitMQ MQ bro broker ker and consume consume fro from m two route key keys: s: - submi submit.sm. t.sm.*: All mes messag sages es sen sent t thr throug ough h SMP SMPP P Con Connec nector tors s - submi submit.sm. t.sm.resp resp. .*: Mor More e rel releva evant nt tha than n Sub Submit mitSM SM bec becaus ause e it con contai tains ns the sen sendin ding g sta status tus

Note: - Messa Messages ges consu consumed med from submi submit.sm. t.sm.resp resp. .*   are not ver verbos bose e eno enough ugh, , the they y con contai tain n onl only y mes messag sage-i e-id  d  - Mes Messag sage e con conten tent t can be obt obtain ained ed fro from m sub submit mit.sm .sm. .*, th the e me mess ssag agee-id id wi will ll be th the e sa same me wh when en co cons nsu u it is us used ed fo for r ma mapp ppin ing. g. - Bil Billin ling g inf inform ormati ation on is con contai tained ned in mes messag sages es con consum sumed ed fro from m sub submit mit.sm .sm. .* - Th This is is a pr proo oof f of co conc ncep ept, t, sa sayi ying ng an anyo yone ne ca can n co cons nsum ume e fr from om an any y to topi pic c in Ja Jasm smin in's 's ex exch chan ange ge ha third party busin business, ess, more info informati rmation on here: http: http://do //docs.ja cs.jasmins sminsms.c ms.com/en om/en/late /latest/m st/messag essaging/i ing/i """ host   =   '127.0.0.1' port   =   5672 vhost   =   '/' username   =   'guest' password   =   'guest' spec_file   =   '/etc/jasmin/reso '/etc/jasmin/resource/amqp0-9-1.xm urce/amqp0-9-1.xml' l' spec   =   txamqp. txamqp.spec spec. .load(spec_file) Connec nect t and aut authen hentic ticate ate # Con d   =   ClientCreator(reactor, AMQClient, delegate= delegate =TwistedDelegate(), vhost= vhost =vhost, spec= spec =spec) spec). .connectTCP(host, port) addCallback(gotConnection, onnection, username, password) d.addCallback(gotC

def   whoops(err): whoops(err): if   reactor. reactor.running: log.err(err) log. reactor. reactor .stop() d.addErrback(whoops) reactor.run() reactor.

3.14.2 How to directly access access the Perspective Perspective Broker Broker API ? Management tasks can be done directly when accessing   PerspectiveBroker API, PerspectiveBroker  API, it will be possible to: • Manage SMP SMPP P Client connectors, • Check status of all connec connectors, tors,

3.14. Developer FAQ

89

 

Jasmin Documentation, Release 0.9.3-beta

• Send SMS, • Mana Manage ge User Userss & Groups, Groups, • Mana Manage ge Rout Routes es (MO / MT), MT), • Access statistics, • ... Here’ss an example: Here’ # Gist from https://gist.git https://gist.github.com/farirat/ hub.com/farirat/922e1cb2c4782660c 922e1cb2c4782660c257  257  """ An exa exampl mple e of sce scenar nario io wit with h the fol follow lowing ing act action ions: s: 1. Ad Add d an and d st star art t a SM SMPP PP Cl Clie ient nt co conn nnec ecto tor  r  2. Pro Provis vision ion a Def Defaul aultRo tRoute ute to tha that t con connec nector  tor  3. Pro Provis vision ion a Use User  r  This Thi s is a dem demons onstra tratio tion n of usi using ng PB (Pe (Persp rspect ective iveBro Broker ker) ) API to gai gain n con contro trol l Jas Jasmin min. . The jas jasmin min SMS gat gatewa eway y sha shall ll be alr alread eady y run runnin ning g and hav having  ing  a pb li list sten enin ing g on 89 8989 89. . """

import   cPickle   as   pickle reactor, defe defer r from    twisted.internet   import   reactor, from  from    jasmin.managers.proxies   import  SMPPClientManagerPBProxy from  from   jasmin.routing.proxies   import   RouterPBProxy from   from   jasmin.routing.Routes   import   DefaultRoute from   from  from  jasmin.routing.jasminApi  jasmin.routing.jasminApi   import   User, Grou Group p from  from  jasmin.protocols.smpp.configs  jasmin.protocols.smpp.configs   import   SMPPClientConfig from  jasmin.protocols.cli.smppccm  from  jasmin.protocols.cli.smppccm    import   JCliSMPPClientConfig   as   SmppClientConnector from   from   twisted.web.client   import   getPage @defer.inlineCallbacks def   runScenario(): runScenario(): try: First st par part, t, SMP SMPP P Cli Client ent con connec nector tor man manage agemen ment t ## Fir ################################## ################# ############################## ############# # Con Connec nect t to SMP SMPP P Cli Client ent manageme management nt PB pro proxy  xy  proxy_smpp   =  SMPPClientManagerPBProxy() proxy_smpp.connect( connect('127.0.0.1' '127.0.0.1', ,   8989, 8989,   'cmadmin', 'cmadmin',   'cmpwd') 'cmpwd') yield   proxy_smpp. Provis vision ion SMP SMPPCl PClien ientMa tManag nagerP erPBPr BProxy oxy wit with h a con connec nector tor and sta start rt it # Pro connector1   =   {'id': 'id':'abc' 'abc', ,   'username': 'username':'smppclient1', 'smppclient1',  'reconnectOnConnectionFailure':  'reconnectOnConnectionFailure':True True} } config1   =   SMPPClientConfig(**connector1) proxy_smpp.add(config1) yield   proxy_smpp. yield   proxy_smpp. proxy_smpp.start( start('abc' 'abc') ) ## Sec Second ond par part, t, Use User r and Rou Routin ting g man manage agemen ment t ########################################### # Co Conn nnec ect t to Ro Rout uter er PB pr prox oxy  y  proxy_router   =   RouterPBProxy() yield   proxy_router. proxy_router.connect( connect('127.0.0.1' '127.0.0.1', ,   8988, 8988,   'radmin' 'radmin', ,   'rpwd') 'rpwd') # Pro Provis vision ion Rou Router terPBP PBProx roxy y wit with h MT rou routes tes yield   proxy_router. proxy_router.mtroute_add(Def mtroute_add(DefaultRoute(SmppCli aultRoute(SmppClientConnector( entConnector('abc' 'abc')), )),   0) routes   =   yield   proxy_router. proxy_router.mtroute_get_all()  print   "Configured "Configured routes:   \n\t%s %s" "   %   pickle. pickle.loads(routes)

90

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

# Pro Provis vision iong g rou router ter wit with h use users rs g1   =   Group(1 Group(1) u1   =   User(uid   =   1, gro group up   =   g1, username username   =   'foo', 'foo', pass password word   =   'bar') 'bar') proxy_router.group_add(g1) yield   proxy_router. yield   proxy_router. proxy_router.user_add(u1) users   =   yield    proxy_router. proxy_router.user_get_all()  print   "Users:   \n\t%s %s" "   %   pickle. pickle.loads(users) Last st, , te tear ar do down wn ## La ################## # Sto Stop p con connec nector  tor  yield   proxy_smpp. proxy_smpp.stop( stop('abc' 'abc') ) Exception, e: except   Exception,  print   "ERROR "ERROR RUNN RUNNING ING SCEN SCENARIO: ARIO:   %s %s" "   %   str str(e) (e) finally: reactor. reactor .stop() runScenario() .run() reactor. reactor

3.14.3 Can you provide provide an example of how to use EvalP EvalPyFilter yFilter ? Let’s say you need your filter to pass only messages from username foo: if   routable. routable.user user. .username   ==   'foo': 'foo': result   =   False

else: result   =   True

Note:   Although UserFilter is already there to provide this feature, this is just a simple example of using EvalPyFilter. EvalPyFilter.

So your python script will have a  routable  global variable, it is an instance of   RoutableDeliverSm if you’re playing with a MO Route and it will be an instance of   RoutableSubmit RoutableSubmitSm Sm if you’re considering it with a MT Route. In order to implement your specific filter, you have to know all the attributes these objects are providing, Now let’s make an advanced example, the below filter will: • Conne Connect ct to a database database • Check iiff the messag messagee  destination_address  is in   blacklist blacklisted_numbers ed_numbers table • Pass only if if the  destination_address  is not blacklisted """Thi This s is an exa exampl mple e of usi using ng Eva EvalPy lPyFil Filter ter wit with h a dat databa abase se int interr erroga ogatio tion, n, it is wri writte tten n """ for demo demonstra nstration tion purp purpose ose only only. . """

import   MySQLdb   as   mdb destination_addr   =   routable. routable.pdu pdu. .params[ params['destination_addr' 'destination_addr'] ]

try: con   =   mdb. mdb.connect( connect('localhost' 'localhost', ,   'jasmin', 'jasmin',   'somepassword', 'somepassword',   'jasmin_faq'); 'jasmin_faq');

cur   =   con. con.cursor() cur.execute( cur. execute("SELE "SELECT CT COUNT COUNT(msis (msisdn) dn) FROM black blacklist listed_nu ed_numbers mbers WHERE msisd msisdn n =   %s %s" "   %   destination_  count   =   cur. cur.fetchone()

3.14. Developer FAQ

91

 

Jasmin Documentation, Release 0.9.3-beta

if   count[0 count[0]   ==   0: # It is no not t bl blac ackl klis iste ted, d, fi filt lter er wi will ll pa pass ss result   =   True except   mdb. mdb.Err Error, or, e: erro ror, r, fi filt lter er wi will ll bl bloc ock k # A DB er # Er Erro ror r ca can n be lo logg gged ed as we well ll .. ... . result   =   False

finally: # Fi Filt lter er wi will ll bl bloc ock k fo for r an any y ot othe her r ex exce cept ptio ion n / re reas ason on result   =   False

3.14.4 How to log events events inside an EvalPyFilter EvalPyFilter ? It is a usual method to get the filter logging directly to the Router’s log file (default is  router.log), here’s a very simple example of doing it: import   logging log   =   logging. logging.getLogger( getLogger("jasmin-router" "jasmin-router") ) log.debug( log. debug('Inside 'Inside evalpy-test.py') evalpy-test.py')

if   routable. routable.user user. .username   ==   'Evalpyusr2': 'Evalpyusr2': log. log .info( info("Rout "Routable able's 's usern username ame is Evalp Evalpyusr2 yusr2 !") !" ) result   =   False else: log. log .info( info("Rout "Routable able's 's usern username ame is not Eval Evalpyusr pyusr2: 2:   %s %s" "   %   routable. routable.user user. .username) result   =   True

Note:   More on python python logging: here logging: here..

3.14.5 How to set an EvalPyFil EvalPyFilter ter for a MT Route ? I have written my  EvalPyFilter , how can i use it to filter MT messages ? Using jCli: First, create your filter: jcli jcli : filt filter er -a Addi Adding ng a new new Filt Filter er: : (ok: (ok: save save, , ko: ko: exit exit) ) > type eval evalpyfil pyfilter ter > pyCode /some/path/advan /some/path/advanced_evalpyfilter. ced_evalpyfilter.py py > fid blacklist_ blacklist_check check > ok Successful Succe ssfully ly added Filter Filter [Eva [EvalPyFi lPyFilter lter] ] with fid: fid:black blacklist list_chec _check k

Second, create a MT Route: jcli jcli : mtro mtrout uter er -a Addi Adding ng a new new MT Rout Route: e: (ok: (ok: save save, , ko: ko: exit exit) ) > type Stat StaticMTR icMTRoute oute jasmin.routing.Routes.StaticMTRou jasmin.routing.R outes.StaticMTRoute te arguments: filte filters, rs, connector connector, , rate > filte filters rs blacklist blacklist_chec _check k

92

Chapter 3. Full contents

 

Jasmin Documentation, Release 0.9.3-beta

> conne connector ctor smpp smppc(SOM c(SOME-SM E-SMSC) SC) > ra rate te 0. 0.0 0 > or orde der r 10 > ok Successful Succe ssfully ly added MTRoute MTRoute [Sta [StaticMT ticMTRoute Route] ] with order order:10 :10

And you’re done ! test your filter by sending a SMS through Jasmin’s APIs.

3.14. Developer FAQ

 

Jasmin Documentation, Release 0.9.3-beta

93

94

Chapter 3. Full contents

 

CHAPTER 4

Links

•  Jasmin SMS Gateway home page •   Documentation •  Source code •   Travis CI

95

 

Jasmin Documentation, Release 0.9.3-beta

96

Chapter 4. Links

 

CHAPTER 5

License

Jasmin is released under the terms of the [Apache License Version 2]. See ‘LICENSE‘  file for details.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close