{{announcement.body}}
{{announcement.title}}
Refcard #322

Getting Started With Ballerina

Ballerina is a network-distributed programming language, and its general syntax is based on C, Java, and JavaScript style. Ballerina is centered around a sequence diagram model and built upon unique abstractions that bring the network aspect into the programming language itself.

Published: Jan. 02, 2020
1,781
Free PDF for easy Reference

Brought to you by

WSO2
refcard cover

Written by

author avatar Anjana Fernando Director, WSO2 Inc.
asset cover
Refcard #322

Getting Started With Ballerina

Ballerina is a network-distributed programming language, and its general syntax is based on C, Java, and JavaScript style. Ballerina is centered around a sequence diagram model and built upon unique abstractions that bring the network aspect into the programming language itself.

Published: Jan. 02, 2020
1,781
Free PDF for easy Reference

Written by

author avatar Anjana Fernando Director, WSO2 Inc.

Brought to you by

WSO2
Table of Contents

Introduction

Installation and Tooling

Code Structure

Fundamentals

Concurrency

Docker and Kubernetes

AWS Lambda

Resiliency

Observability

Taint Analysis

Section 1

Introduction

Ballerina is a network-distributed programming language. This is built upon unique abstractions that bring the network aspect into the programming language itself. As a result, Ballerina treats aspects such as network services, endpoints, and actions as first-class citizens of the language.

Ballerina is seen as a natural evolution toward a shift in general programming; thus, we cannot ignore the network as a major part of modern programming anymore. The Ballerina language design is also centered around a sequence diagram model, which is used in visualizing your network-distributed application.


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 2

Installation and Tooling

Ballerina is a language designed with multiple implementations. The current implementation is running on top of the JVM, known as jBallerina. There is also an LLVM-based native implementation in the works, which can be used to compile Ballerina code to platform-specific binaries.

Ballerina compiler packages for each major operating system can be downloaded here: https://ballerina.io/downloads/ 

Ballerina contains a project concept, but a single source file can also be run simply by following the below format: 

 $ ballerina run <source_file>  


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 3

Code Structure

A Ballerina project can be created by using the command  ballerina new <project-name> . For each project, a  Ballerina.toml  file that contains project-specific information is generated, including the organization, which can be set by the user. A single organization can contain many modules. 

A module can be created using the command  ballerina add <module-name> . Each Ballerina module contains a set of functions, module level variables, and custom type definitions (e.g., records, objects, etc.). After implementing the modules in a project, they can be pushed to a local/remote Ballerina repository by using the  ballerina push  command. 

This will push and store the modules inside its organization grouping. You can reference an existing module by providing the organization name and the module name to be imported.


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 4

Fundamentals

The general syntax of Ballerina is based on C, Java, and JavaScript style. If you have programmed in similar style languages before, you will feel at home with Ballerina.

Type System

Ballerina is a statically typed language that contains dynamic typing properties by means of union types. 

Simple Types

NAME 

VALUES 

 ()  

 () ,  null  (nil or missing value) 

 boolean  

 true ,  false  

 int  

42, -71, 0xFF (64-bit signed integers) 

 byte  

10, 50, 0xA4 (8-bit unsigned integers) 

 float  

1.0 1e-17 1f (64-bit binary floating point) 

 decimal  

1.0 1.50d (128-bit decimal floating point) 

 string  

"\u[1f600]" "Hello world" (Unicode strings) 


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 5

Concurrency

Ballerina implements a rich concurrency model based on a lightweight worker concept to run parallel executions. The workers cooperate with each other by sharing CPU resources when executing non-blocking I/O and other tasks.

Workers

JavaScript




xxxxxxxxxx
1
14


 
1
public function main(string... args) {
2
    worker w1 {
3
        int a = 10;
4
        // concurrent work
5
        // send message to worker w2
6
        a -> w2;
7
    }
8
    worker w2 {
9
        int b;
10
        // concurrent work
11
        // receive message from worker w1
12
        b = <- w1;
13
    }
14



This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 6

Docker and Kubernetes

Ballerina supports many deployment options. For microservices development and deployment especially, Docker and Kubernetes are the frontrunners. Ballerina contains built-in features for generating Docker and Kubernetes artifacts. 

Java




xxxxxxxxxx
1
13


1
import ballerina/http;
2
import ballerina/kubernetes;
3

          
4
@kubernetes:Service {
5
    serviceType: "LoadBalancer"
6
}
7
@kubernetes:Deployment { }
8
service myservice on new http:Listener(8080) {
9
    resource function doit(http:Caller caller, http:Request request)
10
    returns error? {
11
        _ = check caller->respond("Hello!");
12
    }
13
}


 $ ballerina build test_service.bal 

Shell




xxxxxxxxxx
1


 
1
Compiling source
2
    test_service.bal
3

          
4
Generating executable
5
    @kubernetes:Service - complete 1/1
6
    @kubernetes:Deployment - complete 1/1
7
    @kubernetes:Docker - complete 3/3
8
    @kubernetes:Helm - complete 1/1


Run the following command to deploy the Kubernetes artifacts: 

  $ kubectl  apply -f /test_service/kubernetes/ 

Run the following command to install the application using Helm:

  $ helm in stall --name test-service-deployment /test_ service/kubernetes/test-service-deployment


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 7

AWS Lambda

A popular serverless platform as a function-as-a-service is AWS Lambda. Ballerina provides a convenient approach for directly deploying Ballerina functions as lambda functions in the AWS Lambda environment.

Java




xxxxxxxxxx
1
11


 
1
import ballerinax/awslambda;
2

          
3
@awslambda:Function
4
public function echo(awslambda:Context ctx, json inp) returns json|error {
5
    //ctx.getDeadlineMs();
6
    //ctx.getRemainingExecutionTime();
7
    //ctx.getInvokedFunctionArn()
8
    //ctx.getRequestId()
9
    //ctx.getTraceId();
10
    return inp
11
}


 $ ballerina build aws-lambda-functions.bal  

Shell




xxxxxxxxxx
1


 
1
Compiling source 
2
    aws-lambda-functions.bal 
3
Generating executables 
4
    aws-lambda-functions.jar 
5
    @awslambda:Function: echo 



This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 8

Resiliency

In a microservices architecture, resiliency is a critical behavior for having a reliable system. Ballerina follows a set of well-known patterns for addressing this.

Circuit Breaker

Circuit breaker pattern is used to protect us from making unnecessary calls to a continuously failing backend service to avoid resource exhaustion.

Java




xxxxxxxxxx
1
19


1
http:Client clientEP = new ("http://example.com:8080", {
2
    circuitBreaker: {
3
        rollingWindow: {
4
            timeWindowInMillis: 10000
5
        },
6
        failureThreshold: 0.2,
7
        resetTimeInMillis: 10000,
8
        statusCodes: [400, 404, 500] // status codes considered as errors 
9
    }
10
});



This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 9

Observability

A critical aspect of a microservices architecture is observability. To monitor its health, debug it, and optimize its performance, we need observability technologies. Ballerina comes with out-of-the-box functionality to observe your applications and a user library for extended functionality.

Observability features in Ballerina can be enabled by setting the  b7a.observability.enabled  property to  true 

 $ ballerina run <src> --b7a.observability.enabled=true 


This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

Section 10

Taint Analysis

Ballerina follows an inherently secure policy. Taint analysis is a feature in Ballerina to ensure developers explicitly enforce data security. This is implemented by marking program variables as tainted or untainted, which allows you to express your requirement in consuming and generating explicit tainted or untainted values.

In Ballerina, all values are untainted unless they are explicitly made tainted by casting it using  <@tainted> 

Java




xxxxxxxxxx
1


 
1
int a = 5; // a is untainted
2
int b = <@tainted> 10; // b is tainted


In function parameters, we can express our requirement by annotating the parameters as untainted or not. 

Java




xxxxxxxxxx
1


1
function secureFunction(@untainted int p1) { 
2
    // function that only accepts untainted values 
3


The above function,  secureFunction , takes in a single parameter,  p1 , which is marked as requiring an untainted value. Invoking this function using the earlier defined two variables,  a  and  b , is shown below: 

Java




xxxxxxxxxx
1


 
1
secureFunction(a); // success
2
secureFunction(b); // error: tainted value passed to untainted parameter 'p1'



This is a preview of the Getting Started With Ballerina Refcard. To read the entire Refcard, please download the PDF from the link above.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}