Our Blog

AWS Lambda Tutorial: Step by step instructions to create a scalable web application – Part 4

Arunbalan
January 27, 2016
535337722_5fd0c74173_o

Configuring Amazon API Gateway and finishing application

STEP 1: CONFIGURING THE APIS.

Now your lambda functions are ready and functioning. The next step is to enable them to access from the Amazon API Gateway and pass the necessary parameter to each Lambda function.

In the same page where you upload your lambda function click the Get method under the API endpoints tab. Then it directs you to a new page where you can configure your API. A new page will appear as below. Click on your API  (for example –   CreateAccount ).

 

 

  • 105In API Gateway, a mapping template is used to transform some data from one format to another. You create and use input mapping templates when you need to inform API Gateway about the schema of the data that is given to lambda function and you can use output mapping templates for output of the lambda function. You can create models that enable API Gateway to make it easier for you to create mapping templates.
  • Click on the GET method under the Resource tab. You will get a screen like below image.

 

Screenshot from 2016-01-27 00:18:14
    •  Select Method Request from the first box to set the URL Query String Parameters and input model. Click Add query stringunder the URL Query String Parameters section. Enter two  parameters   name and password click and submit . Then set the input model by clicking Add Model, then a new screen will display. Enter the model name as Input Model. In the edit field type the code provided below

      { 
        "$schema": "http://json-schema.org/draft-04/schema#", 
        "title": "CreateAccount", 
        "type": "object", 
        "properties": { 
                       "name": { "type": "string" }, 
                       “password”: {“type”:”string”} 
                      } 
      }

Screenshot from 2016-01-27 00:22:19

Note: Here in this example we are giving two parameters under the properties key, because this model is using for CreateAccountfunction’s API configuration. In order to do the same for UpdateStatus function API we needed to include one more parameter inside the properties. The third parameter is the status parameter.

  • Next Select the Integration Request block and Select the Integration type as Lambda Function, Then Select your lambda function name. You can create a Mapping template under the mapping template section. Under the Content-type tab add application/json and submit. Add codes to mapping template edit window. The sample code is given below.

     { 
       "name": "$input.params(‘name)",
       “password”: “$input.params(“password”)” 
     } 
 Screenshot from 2016-01-27 14:31:20

Now the parameter query string parameter is passed to the here and a new json formatted body is created.

  • Now the parameter required for the lambda function is converted to the well formatted json content. Lambda will pass all parameters after making it as string using JSON.Stringify method. So we need to capture the result and change it into the desired format as we needed.

Select Integration Response section to create an output mapping template. It is similar to the template that we did in Integration Request to create input mapping template. Select the Content-Type as application/json. The HTML page is stored inside a variable. That same string we needed to capture from the lambda function. Follow the code given below


      #set($inputRoot = $input.path('$')) 
      $inputRoot.respon 

Screenshot from 2016-01-27 14:33:47
  • The result is now in JSON format. We need to convert its Content-Type into text/html in order to get an HTML page as output. Otherwise there should be quotes outside the HTML codes.
  • Select Method Response section and add a response model add Content-Type as text/html and create an output model.
  • Enter the output model format in the text field. Example code is given below

     { 
        "$schema": "http://json-schema.org/draft-04/schema#",
        "title": "OutputModel",
        "type": "object",
        "properties": {
                        "resp":{"type":"string"}
                      }
     }
 

 

 

Screenshot from 2016-01-27 14:43:49
    •  Do  the same steps for the other two functions UpdateStatus and getAllStatus . The only difference is that there is an additional parameter required for  the UpdateStatus , ie status . So we should add name,password and status in the URL Query String parameter field of Method Request section. And create a request model and name it as Input then add the input model as the following datas. the only difference from the previous API configuration(CreateAccount) is the presence of status parameter.
 
      {
       "$schema": "http://json-schema.org/draft-04/schema#", 
       "title": "updateStatus", 
       "type": "object", 
       "properties": {
                       "name": { "type": "string" }, 
                       "password":{"type":"string"}, 
                       "status":{"type":"string"}
                     }
      }
 

Add the following template datas in the Integration Request section.


      { 
       "name": "$input.params('name')",
       "password":"$input.params('password')",
       "status" : "$input.params('status')"
      }

The getAllStatus API configuration is same as that of CreateAccount function.

Now the models and mapping templates are ready to use. Next step is deploying the API. There is a button called Deploy APIclick on it. Select a deployment stage and deploy the API . Then you can configure Cache settings, CloudWatch settings and Throttling settings. Invoke url will be displayed on the top of the screen.

  • Now the models and mapping templates are ready to use. Next step is deploying the API. Select a deployment stage and deploy it . Then you can configure Cache settings, CloudWatch settings and Throttling settings. Invoke url will be displayed on the top of the screen.
  • Note down the invoke url. we will send the request to this url from our application.

 

15

 

STEP 2 : CREATE WEB INTERFACE AND UPLOAD IT TO AMAZON S3
  • Everything is ready, now we can invoke the lambda function from a browser by sending the parameter with the invoke url. The sample application interface is located in following link
  • https://s3.amazonaws.com/lambdapackage/LambdaAppFinal/index.html . the code is available herehttps://github.com/Nethram/LambdaDemoApplication/blob/master/index.html
  • Create the application interface. you can refer the given html markups. In index.html file we have given action url of our API endpoint. Replace it with your invoke URL.
  • So the next step is to upload the application interface file to the aws S3. Amazon S3 ( Simple Storage Service ) is an online file storage and web service. The is an button named as Create Bucket. Click on it . The following window will appear.

 

    • 106From the AWS console select S3 from the Storage and Content Delivery section.
    • Give a name to it (example: lambdaApp) and select a region. Then press create button. Then on the next screen there is an option to upload files to S3.  then upload the html file to it.
    • After completing the upload.  write click on the file and select  Properties. Then a window will load on the right side of the page. Select Permission tab from the window. And select the Open/Download   checkbox in the section where grantee name  is set as everyone . Save the changes.
    • Now the page is publically accessible. go to the page and check the functionalities of Your first Lambda Application.
    • The lambda function updates the DynamoDB and RDS and it will return a HTML page to the browser.
16
Your scalable and reliable Lambda application is now ready to use.

AWS Lambda Tutorial: Step by step instructions to create a scalable web application – Part 3

Arunbalan
6937250243_5da87cf012_o

Create and configure Lambda functions and uploading Lambda application packages to AWS

Step 1: Create And Configure the Lambda function.

Sign in to the AWS console and select the Lambda . Then follow the instructions to create a lambda function. This session shows the steps to create first lambda function- CreateAccount  for our application . Follow same steps to create two more functions, that are UpdateStatus andgetAllStatus.

  • Click on Create A Lambda Function button.
  • Select blueprint, choose the  microservice-http-endpoint  blueprint
  • Configure function, specify the following values:
    • Enter a function name (for example,  CreateAccount ).
    • Select Node.js from the  Runtime  list.
    • For the IAM  Role , create a role by choosing the  Basic with DynamoDB  from the list.

This role template has a predefined access policy that grants sufficient permissions for AWS actions that your Lambda function needs.If you need more access permissions for your needs you can  create a new IAM role and assign a name (for example,  lambda_dynamo ) as the execution role. Here we use the predefined template Basic with DynamoDB. Press Allow button then click Next.

  • In Configure endpoints , specify the following values:
    • Give a name to the new API . Here we used the same name of the lambda function (CreateAccount ).  After the API is created, it will appear in the Amazon Gateway console.
    • Leave the  Resource name  as it appears in the console. It maps to the name that you specified for your Lambda function, so do not change this value.Here also we gave the same name of the lambda function( CreateAccount ).
    • Choose a method from the list. Here we have chosen GET method.
    • Leave the default  prod  for  Deployment stage .
    • Choose  Open from the  Security  list.

Note: Make sure you have selected the Open from the Security list. Because we create this function for invoke it from web browsers without authentication process.

You will get a following screen make sure your configurations and click Create function .

 

 

10
Step 2: Creating and Uploading the Lambda Application packages.

There are various options to  deploy lambda function to aws. First one , we can use the editor available in Lambda console. and the second option is  uploading  a lambda package from our local machine to aws as a zip package.  Final option is using lambda package stored in the amazon S3.  In this scenario , we use the second method , that is directly  uploading our lambda package from local machine  to AWS lambda. It is because we are using MySQL database in RDS for this application. For that we need to include additional MySQL module to our package. we can’t do this in the editor available in  Lambda console.

A:Create a Lambda function deployment package

  • Create a folder ( LamdaApp ) in your local machine and create three sub-folders inside it. You may give those names as CreateAccount , UpdateStatus and GetStatus  Respectively. After creating the folders install necessary dependency packages to all these three folders.
  • You need to install Node.js platform.
    • Install the Node.js platform. For more information, go to the Node.js website at http://nodejs.org/.
    • Install dependencies in each folder. First enter in the first folder named CreateAccount and install those required modules.
      • For MySQL module type this in terminal.

                                    sudo npm install mysql

      • For File System module type this line in terminal.

                                    sudo npm install fs

  • This will create a directory called node_modules and install the modules inside it. The mysql module is entirely written in Node.js, and implements an async MySQL.
  • Copy the node_modules folder and paste it to other two folders (UpdateStatus and GetStatus).
  • Now we have 3 folders and their required dependency packages in them. Next step is to create lambda function.

 B: Create lambda function and html contents.

    Inside  each folder create the node.js file and other required files for the execution of the functions such as files containing HTML contents

      CreateAccount

  1. In CreateAccount Folder Create following files. Files contents are available in github .  :https://github.com/Nethram/LambdaDemoApplication
  2. Add contents of the index.js as given in the github file.which contains the actions to be performed after getting required parameters.Modify the  lines 26-30 and add  credentials for your  RDS DB instance that you have created earlier.. Add  the name of DynamoDB table in line number 58.
  3. The successful.txt contains the HTML markups which is to be shown after successfully creating an user account.
  4. The unsuccessful.txt contains the HTML markup that will return after errors occurred.

 

       UpdateStatus

  1. Inside the updateStatus folder Create following files.
  2. Add contents of the index.js as given in the github file.which contains the actions to be performed after getting required parameters such as username, password and status.Modify the  lines 25-29 and add  credentials for your  RDS DB instance that you have created earlier. Add  the name of DynamoDB table in line number 61
  3. The success.txt file contains the HTML markups which is to be shown after successful updating of users status.
  4. The incorrect.txt files contains the HTML content which will show after incorrect user password entry.
  5. The noexistuser.txt  contains the HTML contents which show the given username is not created an account. index.js.

 

       GetAllStatus.

  1. Inside the updateStatus folder Create following files.
  2. Add contents of the index.js as given in the file in github. this is the page which executes when we trigger the lambda.Modify the  lines 26-30 and add  credentials for your  RDS DB instance that you have created earlier.Add  the name of DynamoDB table in line number 71.
  3. The success.txt file contains HTML markups which is to be shown after successful authentication of user credentials. This                  contains the HTML format of returning every user’s status.
  4. The incorrect.txt file contains the HTML content which will show after incorrect user password entry.
  5. The noexistuser.txt  contains the HTML contents which show the given username doesn’t hold an account.

C:Uploading the Lambda package

  • Now we have everything ready inside the LambdaApp folder. The next step is to compress the contents of those three subfolders and make zip files. You need to make sure that you are compressing the contents of each folders and not the folder itself. Upload the zip files to the lambda console of each lambda function. See the image below, there is an option to directly upload your zip packages to it or you can upload the files to amazon S3 then configure the third option. Here we are directly uploading the application package to the lambda.

 

103

 

  •  Test the function by clicking the Action button and select Configure test event  option. then on the next window configuring a sample event by giving the simple JSON body. See this image.

 

104

For example, after uploading the CreateAccount zip package we test the function by giving the parameters such as name and password.   The JSON text event body is like this.


     {
      "name":"janet",
      "password":"janet1234"
     }

  • Click on Save and Test  button. Then the given parameters will be passed to the lambda function and it will execute,ie it will create an user account. The result will be shown in  the console. The console will show error if there is any mistakes in your lambda function code.
  • Check your database table and ensure the new item entry.
  • Follow the same steps to upload and test other two lambda function packages. And use the test event body as follows. For UpdateStatus  function. use this.   
    
         {
            "name":"janet",
            "password":"janet1234",
            “status”: “This is my test status”
         } 
    

    make sure that your dynamoDB table has new entry after the test.

     For  getAllStatus function. use the test event shown in the first example.

 

We will cover the methods to configure API endpoint and upload application to AWS S3  in Part 4

AWS Lambda Tutorial: Step by step instructions to create a scalable web application – Part 2

Arunbalan
maxresdefault

Nuts and Bolts

This  application gives a complete overview of how to use AWS resource (such as DynamoDB and RDS) with Lambda and how to return an HTML page as a  response to every incoming request. Here we are using Amazon RDS for storing user’s account information and Amazon DynamoDB for storing user’s status information. The web app is stored in Amazon S3.  It is important to note that EC2 is not used. Hence there is no reserved infrastructure.
Note: There is no need to use both RDS and DynamoDB simultaneously. This example is using both to show that lambda can interface with both.

We will create 3 lambda functions and invoke these functions from separate API endpoints. The Lambda functions are

  • CreateAccount : This function is used to create an account for the user by receiving username and password.
  • UpdateStatus   : This function receives username, password and status from the user. And update the status after authentication.
  • GetAllStatus    : This function authenticates users and list status of every user.

You are just few steps away from creating your Lambda application.

STEP 1: BEFORE YOU USE AWS LAMBDA FOR THE FIRST TIME, COMPLETE THE FOLLOWING TASKS:
  1. Go to the website https://aws.amazon.com/
  2. Sign up for AWS.
STEP 2: CREATE AMAZON RDS MYSQL  AND DYNAMODB DATABASES.

a. Create and configure RDS MySQL database instance

 

3rd

 

  • Click on Launch a DB Instanceand Select MySQL database engine.
  • In Production panel select Second Option MySOL – use Multi-AZ Deployment and Provisioned IOPS Storage as defaults for high availability and fast, consistent performance. Click next button.
Screenshot from 2016-01-27 22:10:24

 

  • Specify database details in next step. Modify database instance class as you need. Here we select db.t2.micro and availing Multi-AZ Deployment. Under the settings give database name, username and password.
6
  • Note down these RDS credentials,which are required to make DB connection from NodeJS script.
  • Here comes an important configuration setup. In this page given below  you should make the database publically accessible. And choose VPC and  default VPC Security group. Then give a name to your database. Then click Launch DB Instance.

 

7

   

 

 

  • Then your database will be created. You will get the endpoint address from the properties of that instance.
  • Install mysql client and connect to this database using endpoint address, username and password. And add the schema given in our github. (in this demo application. We created a table named as ‘login’ and add three fields >UserId , name and password. UserId is auto incremented and name is the Primary key).
  • Download the schema of RDS database available in github  to your system. Open terminal and type commands as in following formate to import schema to RDS.
  • mysql -h RDSEndPointAddress -P 3306 -u username -p databasename < PathTORDSdatabaseSchema.sql 
    


    For example

    
    mysql -h lambdaInstance.cukvxrgt8kqg.us-east-1.rds.amazonaws.com -P 3306 -u user -p lamdaApp < RDSdatabaseSchema.sql
    
    

    Give password.It will configure your database.

 

 

bCreate DynamoDB Table.

  • Go to this link https://console.aws.amazon.com/dynamodb/home and select Create Table option. You will get the following screen. Choose a name for your table and Choose a primary key type. You can choose whatever name you like. For this application we created table lambdaApp. This table name is required to connect with DynamobDB from Nodejs script. So note down this table name.  Here we are choosing hash for primary key and our hash attribute name is UserId. Then Click Continue.

 

8

 

  • On the next page we have not configured the indexes . Leave this page as is.
  • Next page you can configure the throughput capacity. This can be done according to the requirements.
  • In the final page you can enable basic alarm for your table. Provide your email id to get the notification. Press Continue.
  • Now you can review your table configuration and create  the table. After some time the table will be in the active state. Then you can use the database from our lambda function by requesting with the table name and hash primary key.
  • Click on the table name then it will open the table status. see the below image.

 

100

 

  • Then go to the Item tab and press Create Item button. then following window will pop up.

 

101

 

  • click on the plus( + ) button ,it will show three options, select the Append option then select String from the dropdown list.
  • After this you can add the items. In this application we use 3 items. The UserId is already created. so add Name and Status to this table then save it.

 

We will cover the methods to create and deploy lambda applicatioin package  in Part 3

AWS Lambda Tutorial: Step by step instructions to create a scalable web application – Part 1

Arunbalan
speedometer-653246_1920

Building scalable systems is often unmanageable even with cloud computing. Normally we  use Amazon AWS with  EC2 , load balancer and autoscaling. This approach is inconvenient and sudden traffic spikes cannot be handled with autoscaling. Additionally some infrastructure should be always kept in reserve.

Aws Lambda can be used to  solve these hassles of  AWS load balancing.  AWS Lambda is quite promising, easy to use  and does not have the above limitations. The trick of using AWS Lambda with Amazon API gateway can help you  build and scale web-applications with no infrastructure reservations.

AWS Lambda

AWS Lambda is a platform to make completely scalable applications with less effort and without the hassles of virtual machines. You need to upload your application code as “Lambda” functions to AWS. AWS Lambda runs your code on high-availability compute infrastructure and performs all the infrastructure functions, such as administration of the compute resources, capacity provisioning and automatic scaling. Those Lambda functions can be triggered by Amazon API endpoint, thereby exposing to the web. All you need to do is upload your code in one of the languages that AWS Lambda supports (currently Node.js or Java).

 

The Scenario

 

This document includes stepwise procedure for Building a completely scalable and reliable cloud based application using AWS Lambda.In this part we will see working example of scalabe lambda application.This involves creating a web Interface for app, construct AWS Lambda function, configure APIs in Amazon API Gateway and invoke the application from web browser.

This demo application is a poor man’s facebook. The source code is available at github  (https://github.com/Nethram/LambdaDemoApplication) It has 3 functionalities. Those are

  1. Creating user account with username and password.
  2. Update the user’s status.
  3. View every user’s status.

Use this link to test this application. It opens the following interface.

 

 

index_page

 

  • Provide a username and password to create your account.
  • Once an account is created, you may submit your username, password and your status in the second box.
  • You can then see the status of every user by submitting your username and password.

 

2nd

Source Code :https://github.com/Nethram/LambdaDemoApplication.

 

We will cover the nuts and bolts of connecting AWS resources with Lambda in Part2

Howdy- Talk To Strangers is Now Online

Sibin John
May 15, 2015
Screenshot (180)1

About Howdy

Howdy is a voice application that encourages citizens of the world to talk with each other. A person anywhere on the globe can  tap on his phone, connect with a random stranger somewhere else in the globe. They can  speak with each other in order to jointly solve a puzzle, one that can only be cracked by collaborative discussion.  It’s kind of like the world’s biggest game of pub trivia, or a global ice breaker. Howdy games are based on general knowledge, science, history and maths. Howdy is capable of entertaining and at the same time it can be a tool for improving and exchanging knowledge, make friends, have fun, unite the world and at the same time improve your communication skills, general awareness and knowledge base.

Screenshot (180)

How to use

Howdy is a free app and is available at Google Play store. It is also available through web browser. The app is easy to use, once installed the user connects to the Howdy server.  Hit the “Talk” button and they’re connected to a random person and have three minutes to make a connection and say whatever they’d like.

Screenshot (182)

 

By hitting the “Talk ‘n’ Solve” button, they’re connected with a random person and the pair have five minutes to solve the puzzle which can only be done with verbal co-operation and communication.

Screenshot (186)          Screenshot (189)

 

 

 

Users also have an option of leaving a voice message for the rest of the Howdy users. Another Howdy user can retrieve this message by pressing the “Fetch” button, one message will be retrieved – like an electronic note in a bottle.

Screenshot (180)fd

What makes Howdy interesting

Howdy! brings back the excitement of long distance communication.  Once there was a time when talking to someone in another country was a novelty.  Long distance telephone calls were expensive, but the excitement of talking to someone on the other side of the globe was thrilling.  “What’s the weather like there?”  “What are you eating for lunch?”  Just simple questions about our shared daily routines helps to remind us that we’re all one human family.

Additional features and future scope

Security features for Howdy include the ability to block a person and an option to report abuse.

Screenshot (188)

Howdy is built as a platform for building massively scalable web and app based voice applications. The platform can be re-used to build large voice applications such as google talk.

Howdy is available for Android at Google Play store and can be downloaded from https://play.google.com/store/apps/details?id=com.nethram.howdy

Howdy is also available through web browser at  http://howdytheapp.com

Phonepay

Sadique Ali P
March 31, 2015

PhonePay is a web based software tool which helps you to collect payments from your customers via phone calls. It provides an interactive voice response system with assigned Twilio phone number and payment is made through stripe.

Consider Mr. John Doe and his Pizza Hut where he is using PhonePay as a payment option. His customers give  their orders through  phone or some other means. They are advised to call his PhonePay number and pay the billed amount.

John Doe is able to verify their payments in PhonePay’s admin panel. If customer cancels order or if he wish to give some discount , he can refund the desired amount to the customer from admin panel. Also if the customer expands his order, shopkeeper is able to charge overage at any time by a single click.

 

Features

  • Detailed call and transaction log.
  • One click refund.
  • One click overage charging.
  • Configurable system behavior.
  • Simple installation.
  • Easy to use Admin Panel.
  • Responsive design.

Prerequisite

    A web server :

PhonePay run on PHP-MySql enabled web server.

    Stripe Account:

You should have a working Stripe account to collect your payments.You can create a free account by registering at www.stripe.com.

    Twilio Phone number:

Set up a working phone number at www.twilio.com. Your customers have to call this number while attempting to pay for your service

or product.

 

Get Started

It is easy to get started with phone pay. Get a copy of source file from www.github.com. Extract all files to your web server and open it in your favorite web browser. PhonePay’s installer GUI will help you in completing installation. During installation you will be asked to enter database credentials and Stripe keys.

After installation you have to enable your  Twilio number by changing its Request URL. This is done from the the  Twilio account at www.twilio.com. Request URL for PhonePay installed at www.myphonepay.com will be http://www.myphonepay.com/twiml.php.

Now you have a working PhonePay service. Make your first call to your PhonePay number, you will be answered by PhonePay’s IVR.

 

How it works

Users calling to your PhonePay’s number will be answered by its interactive voice response system (IVR) .The user will be lead to pay through Stripe. User will be prompted to enter credit card details by IVR. PhonePay does not store any credit card details on server. All call logs and payment details will be available in Admin Panel. Admin can manage orders and also if needed, refund the amount to the payer. If any customer updates his order, admin is able to charge overage by a single click in admin panel.

Phone Pay can be configured in four different modes called system behavior. System behavior is switchable based on your needs at any time from admin panel.The four system behaviors are as follows.

 

  1. Fixed Payment with Order IDAdmin fixes an amount for all payments. User will be asked to enter Order ID and then lead to pay the fixed amount. Also admin can create order with order ID and payable amount. User entering an existing order ID will be lead to pay corresponding amount.
  2. Fixed Payment without Order IDUser will be directly lead to pay a fixed amount that has set by admin. No Order ID will be asked.
  3. User defined Payment with Order IDUser will be asked to enter the amount they wish to pay after entering Order ID. Also admin can create order with order ID and payable amount. User entering an existing order ID will be lead to pay corresponding amount.
  4. User defined Payment without Order IDUser will be lead to pay the amount they wish to pay.

Set a system behavior best suited to your business and start selling with PhonePay. If you have any question or if need any support please write to us at support@nethram.com. Also you can explore and write at PhonePay’s support form for any questions at http://forum.nethram.com.

 

Screen shorts:

phonepay-dashboard 2 3

Server virtualization with KVM and OpenVZ Containers

Sadique Ali P

Server virtualization is a method of dividing computer resources into multiple isolated environments. It hides server resources, including the number and identity of individual physical servers, processors, and operating systems, from server users. Followings are common usage scenarios.

  • Server consolidation: Server consolidation allows an organization to decrease the number of physical servers, by moving their applications into virtual environments. This leads to savings in hardware costs, rack space, electricity, and management efforts.
  • Security: It provides improved security by putting each network service (like web server, database server,mail server, etc.) into a separate isolated virtual environment. Security  hole in one will not affect other services.
  • Hosting: OS-level virtualization is used in hosting services. Service providers can use this to
  • sell affordable cheap VEs to their customers.
  • Software development and testing: Developers and testers often need access to a handful of Linux distributions, and may need to reinstall  those from scratch. Using virtualization, they can operate multiple distributions using a single server, without rebooting, with native performance. In addition to these, creating and cloning a virtual environment is very easy.
  • Education: By using VE, students can  play with different operating systems in a single physical device.

KVM and OpenVZ Containers

Kernel-based Virtual Machine (KVM) and Container-based virtualization are two commonly used virtualisation techniques.

KVM is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V). Using KVM, one can run multiple virtual machines using unmodified Linux or Windows images. Each virtual machine has private virtualized hardware such as a network card, disk, graphics adapter, etc. In KVM an extra layer of abstraction between the operating system and hardware will be present, and some performance issues may occur depending upon the  physical device. Disk space and RAM will be reserved and disk volumes will be encrypted in KVM. KVM gives full virtualisation – its kernel or virtual hardware is not shared with any machine.

OpenVZ is container-based virtualization for Linux. OpenVZ creates multiple secure, isolated Linux containers on a single physical server. It enables better server utilization and ensures that applications do not conflict. Each container acts and executes exactly like a stand-alone server. Any container can be rebooted independently and have root access, users, IP addresses, memory, processes, files, applications, system libraries and configuration files. In container-based virtualization, disk space and RAM will not be reserved,  it will be allocated dynamically. Its  kernel is shared among containers and there is no encryption for disc volume.

 

Virtualization with ProxMox

Proxmox VE is an open source virtualization management solution for servers. It is based on KVM virtualization and container-based virtualization and manages virtual machines, storage, virtualized networks and HA Clustering. It is optimized for performance and usability. Enhanced Web-based management interface makes it easy to use , there is  no need to install any additional management tools.

Try in Virtual Box

Following paragraph will help you to try ProxMox VE in Virtual Box.

Step :1

Download ProxMox VE image from http://proxmox.com/en/downloads/category/iso-images-pve .

Step:2

Create new virtual machine in your VirtualBox by selecting type Linux and version. Ubuntu 64 bit or any other debian based version. Allocate RAM 1gb as minimum requirement and choose disc and other options best suited to you.
Read more about minimum requirement at http://proxmox.com/en/proxmox-ve/requirements

Step:3

Enable network adapter and select Host-only adapter. Then set image file or CD/DVD in storage tab and start the machine.

virtual box host only network for proxmox install proxmox

Step :4

Install Proxmox VE.

Set country, time zone and password. This will be your log in password to Proxmox VE.

set proxmox

Step :5

Set host name, a fully qualified domain.

By pressing next, Proxmox VE installation will be started.

Step : 6

After completing installation remove CD and reboot machine.

First boot may take a few minutes.

Login as root with password you set at beginning of installation.

 

proxmox in virtual box

Step :7

You are almost done.

Now go to ip displayed in proxmox screen(example:  https://192.168.56.101:8006)

It is available over https only.

Now you might reached in Proxmox VE web interface. Login with root and password set earlier.

 

proxmox-web interface

You can create virtual machines and Open Viz containers using graphical interface in it.

WebRTC with Asterisk 12

Sachin Murali . G
March 18, 2015
WebRTC logo

Using webRTC you can directly enable calls from browser without installing softwares like microsip (Google Chrome or Mozilla Firefox needed) . This tutorial assumes the user to have basic knowledge of Asterisk, Ubuntu and WebRTC. Asterisk 12.7.0 and Ubuntu 14.04 was used to setup the system.

Step 1: Install Updates

sudo apt-get update 
sudo  apt-get upgrade

Step 2 : Install Dependencies

sudo apt-get install build-essential libsqlite3-dev libxml2-dev libncurses5-dev libncursesw5-dev libiksemel-dev libssl-dev libeditline-dev libedit-dev curl libcurl4-gnutls-dev libjansson4 libjansson-dev libuuid1 uuid-dev libxslt1-dev liburiparser-dev liburiparser1 git autoconf libbfd-dev -y

Step 3 : Install SRTP stuff

cd /usr/src
sudo git clone https://github.com/cisco/libsrtp.git
cd libsrtp/
sudo autoconf
sudo ./configure CFLAGS=-fPIC --prefix=/usr
sudo make 
sudo make runtest (you should get an Success message after this)
sudo make install

Step 4 : Install PJ Project

cd /usr/src
sudo git clone https://github.com/asterisk/pjproject pjproject
cd pjproject/
sudo ./configure --prefix=/usr --enable-shared --disable-sound --disable-resample --disable-video --disable-opencore-amr --with-external-srtp
sudo make
sudo make dep
sudo make install

Step 5 : Check pjproject installation

pkg-config --list-all | grep pjproject

(You should see “libpjproject libpjproject – Multimedia communication library” as output)

Step 6: Download and Install Asterisk

cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-12-current.tar.gz
tar -xzf asterisk-12-current.tar.gz
cd asterisk*
cd ./contrib/scripts
sudo ./install_prereq install
sudo ./install_prereq install-unpackaged
sudo ./configure --with-pjproject --with-ssl --with-srtp
sudo make menuselect (make sure you have selected res_http_websocket, res_crypto, chan_sip and res_rtp_asterisk, and all pj modules). Save and exit (F12)
sudo make && sudo make install && sudo make samples && sudo make config

Step 7: Genetate Certificates for DTLS

cd asterisk*
cd ./contrib/scripts
sudo mkdir /etc/asterisk/keys
sudo ./ast_tls_cert -C pbx.mycompany.com -O "My Super Company" -d /etc/asterisk/keys (replace pbx.mycompany.com with the IP of your server or domain name)

Step 8 : Edit /etc/asterisk/http.conf

[general]
enabled=yes
bindaddr=0.0.0.0
bindport=8088

Step 9 : Edit /etc/asterisk/rtp.conf

[general]
rtpstart=10000
rtpend=20000
icesupport=yes
rtpchecksums=no
strictrtp=no
stunaddr=numb.viagenie.ca (or your stun server)
turnaddr=numb.viagenie.ca
turnusername=username
turnpassword=password

Step 10: Configure sip.conf

[general]
udpbindaddr=0.0.0.0:5060
realm=123.123.123.123 (replace with your Asterisk server public IP address or host)
transport=udp,ws
localnet=123.123.123.123/255.255.255.0 (your localip, see command ifconfig)
externaddr = 123.123.123.123 (your public ip)

[6001]
host=dynamic
secret=password
context=from-internal
type=friend
encryption=yes
avpf=yes
force_avp=yes
icesupport=yes
directmedia=no
disallow=all
dial = SIP/6001
allow=ulaw
dtlsenable=yes
dtlsverify=fingerprint
dtlscertfile=/etc/asterisk/keys/asterisk.pem
dtlscafile=/etc/asterisk/keys/ca.crt
dtlssetup=actpass

Step 11: Edit /etc/asterisk/res_stun_monitor.conf

stunaddr = numb.viagenie.castunrefresh = 30

Step 12 : Edit /etc/asterisk/extensions.conf

[from-internal]
exten => 1000,1,Answer()
same => n,Playback(demo-congrats)
same => n,Hangup()

exten => 6001,1,Answer()
same => n,Dial(SIP/6001)
same => n,Hangup() 

Step 13 : Open Firewall ports

sudo ufw allow 5060
sudo ufw allow 8088
sudo ufw allow 10000:20000/udp   

Step 14 : Reboot system

sudo reboot

You have successfully set up a webrtc enabled system now, You can try it using sipml5.org or http://tryit.jssip.net/

sipml5 settings:

Display Name : something
Private Identity : 6001
Public Identity : sip:6001@123.123.123.123 (your server’s public ip)
Password : (secret of 6001)
Realm : 123.123.123.123 (your server’s public ip)

in Expert Settings

Check Enable RTCWeb Breaker

Websocket URL : ws://your.public.ip.address:8088/ws
SIP outbound Proxy URL : udp://your.public.ip.adress:5060
ICE Servers : [{ url: ‘stun:numb.viagenie.ca’}, { url:’turn:numb.viagenie.ca’,username:’user@xxx.com’ ,credential:’myPassword’}]

Check Disable 3GPP Early IMS
Check Cache the media stream

Additional Settings to Enable Video Calling

in sip.conf

[general]
videosupport = yes

and, under each extension, add videosupport=yes and enable codecs as allow=h263, allow=h264 etc.

Onscreen dialpad : Append entries to text field, send dtmf for twilio calls

Sibin John
February 25, 2015
dial

How to create an onscreen dialpad for web pages ? And append the entries from dialpad to a text field. Here is one working example left for you,

This is a custom dialpad used in web twilio , the web client for twilioid app.

 

dial

 

 

CSS


<style>

.btn-primary.active{color:rgba(255, 255, 255, 0.75);}

.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);

background-color:#006dcc;

background-image:-moz-linear-gradient(top, #0088cc, #0044cc);

background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));

background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);

background-image:-o-linear-gradient(top, #0088cc, #0044cc);

background-image:linear-gradient(to bottom, #0088cc, #0044cc);

background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);

border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);

*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}

.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,

.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;}

.btn-primary:active,.btn-primary.active{background-color:#003399 \9;}

</style>

Html

Code to create dialpad :


<table id="dialpad" cellpadding="3%">

<tr id="dial_row1">

<td><input type="button" value="1" id="button1" class="btn btn-primary">

<td><input type="button" value="2" id="button2" class="btn btn-primary"></td>

<td><input type="button" value="3" id="button3" class="btn btn-primary"></td>

<td><input type="button" value=" Clear " id="buttonclear" class="btn btn-warning"></td>

</tr>

<tr id="dial_row2">

<td><input type="button" value="4" id="button4" class="btn btn-primary"></td>

<td><input type="button" value="5" id="button5" class="btn btn-primary"></td>

<td><input type="button" value="6" id="button6" class="btn btn-primary"></td>

<td><input type="button" value="Erase " id="buttonerase" class="btn btn-warning"></td>

</tr>

<tr id="dial_row3">

<td><input type="button" value="7" id="button7" class="btn btn-primary"></td>

<td><input type="button" value="8" id="button8" class="btn btn-primary"></td>

<td><input type="button" value="9" id="button9" class="btn btn-primary"></td>

<td><input type="button" id="accept_button" class="btn btn-success" value="Accept" disabled="disabled"></td>

</tr>

<tr id="dial_row4">

<td><input type="button" value="*" id="buttonstar" class="btn btn-primary"></td>

<td><input type="button" value="0" id="button0" class="btn btn-primary"></td>

<td><input type="button" value="#" id="buttonpound" class="btn btn-primary"></td>

<td><input type="button" id="reject_button" class="btn btn-danger" value="Reject " disabled="disabled"/></td>

</tr>

</table>

and create a text field to append values,

</pre>
<form name="myform">

<input type="text" id="number_to_call"  name="number_to_call" />

</form>
<pre>

Script

 

for appending to text field,


$.each(['0','1','2','3','4','5','6','7','8','9','star','pound','erase','clear'], function(index, value) {

$('#button' + value).click(function()

{

var number=value;

if(number == 'star')

{

document.myform.number_to_call.value += '*';

}

else if(number == 'pound')

{

document.myform.number_to_call.value += '#';

}

else if(number == 'clear')

{

document.myform.number_to_call.value = '';

}

else if(number == 'erase')

{

number =(document.myform.number_to_call.value).slice(0,-1);

document.myform.number_to_call.value = number;

}

&nbsp;

else

{

document.myform.number_to_call.value += number;

}

});

});

for sending dtmf, change the click function as follows,


if (value=='star')

connection.sendDigits('*')

else if (value=='pound')

connection.sendDigits('#')

else

connection.sendDigits(value)

 

Refreshing twilio token programmatically

Sibin John

Twilio Client uses capability tokens to establish communications between devices to Twilio. Capability tokens allow you to add Twilio capabilities to web and mobile applications.

 

Allowing incoming and outgoing capability to a twilio client

 

You create a token on your server and specify what capabilities you’d like your device to have. Here is the code for creating capability token with your twilio credentials (ie. Accountsid and AuthToken). Also download the twilio library from https://github.com/twilio/twilio-php/archive/master.zip and move the twilio-php folder to your project directory and then include the library file, (using php)

 


require '/path/to/twilio-php/Services/Twilio.php';

require '/path/to/twilio-php/Services/Twilio/Capability.php';

$token = new Services_Twilio_Capability(‘Account sid’, ‘AuthToken’);

$token->allowClientOutgoing(‘Appsid’); //enter Appsid of twilio app

$token->allowClientIncoming(‘client name’); // enter client name

Generate tokens


A token can be generated, (using js )


Twilio.Device.setup("<?php echo $token->generateToken();?>");

using php,


$token_name = $token->generateToken();

Life time of tokens and need for refreshing

 

All tokens have a limited lifetime to protect you from abuse. The lifetime is configurable up to 24 hours. By default, this token will expire in one hour. If you’d like to change the token expiration time,generateToken takes an optional argument which specifies time to live in seconds.

in js:


Twilio.Device.setup("<?php echo $token->generateToken(600);?>");//This token will now expire in 10 mins

 

in php:


$token_name = $token->generateToken(600); //This token will now expire in 10 mins

If you are creating applications that requires the twilio client to be online all the time, then this tokens must be refreshed after they expired.

 

For example, web twilio is one of my application that refreshes twilio token every 10 hours.  I used the following simple technique to refresh the twilio token,


Twilio.Device.setup("<?php echo $token->generateToken();?>");

setTimeout(function()

{

location.reload();//reload page every 10hrs to refresh twilio token

}, 36000000);   // 36000000 milliseconds = 10 hours

One disadvantage of this method is that any call in progress, at the time of refreshing page, may be lost. If you want to avoid this problem generate another token in the timeout function.