Run you first gatling load test using scala.

Gatling is a neat tool. You can create your load tests by just coding in scala. Jmeter allows you to do so through a plugin or beanshell but it is not as direct as the way gatling does so.

I will start by adding the gatling plugin

addSbtPlugin("io.gatling" % "gatling-sbt" % "3.0.0")

The next step is to changed the build.sbt


version := "0.1"
scalaVersion := "2.12.8"

enablePlugins(GatlingPlugin)

scalacOptions := Seq(
  "-encoding", "UTF-8", "-target:jvm-1.8", "-deprecation",
  "-feature", "-unchecked", "-language:implicitConversions", "-language:postfixOps")
libraryDependencies += "io.gatling.highcharts" % "gatling-charts-highcharts" % "3.1.2" % "test,it"
libraryDependencies += "io.gatling"            % "gatling-test-framework"    % "3.1.2" % "test,it"

The above are no different than what you can find on the official site when it comes to sbt commands and gatling.

Our next step is to add a simple http test. Be aware that you should add it in the directories src/test or src/it since, as it is instructed from the sbt dependencies for the binaries to take effect on these directories.

I shall put this test on src/test/scala/com/gkatzioura/BasicSimulation.scala

package com.gkatzioura

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class BasicSimulation extends Simulation {

  val httpConf = http.baseUrl("http://yourapi.com")
      .doNotTrackHeader("1")

  val scn = scenario("BasicSimulation")
    .exec(http("request_1")
    .get("/"))
    .pause(5)

  setUp(scn.inject(atOnceUsers(1))).protocols(httpConf)
}

Afterwards testing is simple. You go to sbt mode and execute the test.

sbt
>gatling:testOnly com.gkatzioura.BasicSimulation
>gatling:test

The first command instructs to run just one test, the second one shall run everything.

That’s it! Pretty simple.

Advertisement

Dockerize your Scala application

Dockerizing a Scala application is pretty easy.

The first concern is creating a fat jar. Now we all come from different backgrounds including maven/gradle and different plugins that handle this issue.
If you use sbt the way to go is to use the sbt-assembly plugin.

To use it we should add it to our project/plugins.sbt file. If the file does not exist create it.

logLevel := Level.Warn

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.6")

So by executing

sbt clean assembly

We will end up with a fat jar located at the target/scala-**/**.jar path.

Now the easy part is putting our application inside docker, thus a Dockerfile is needed.

We will use the openjdk alpine as a base image.

FROM openjdk:8-jre-alpine

ADD target/scala-**/your-fat-jar app.jar

ENTRYPOINT ["java","-jar","/app.jar"]

The above approach works ok and gives the control needed to customize your build process.
For a more bootstraping experience you can use the sbt native packager.

All you need to do is to add the plugin to project/plugins.sbt file.

logLevel := Level.Warn

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.4")

Then we specify the main class of our application and enable the Java and Docker plugins from the native packager at the build.sbt file.

mainClass in Compile := Some("your.package.MainClass")

enablePlugins(JavaAppPackaging)
enablePlugins(DockerPlugin)

The next step is to issue the sbt command.

sbt docker:publishLocal

This command will build your application, include the binaries needed to the jar, containerize your application and publish it to your local maven repo.

Run code on startup with Play and Scala

Depending on various projects, sometimes there is the need to execute some actions on initialization just before our application starts to serve requests.

It was a common practice to call the functions that we wanted to get executed through GlobalSettings, however it is not recommended.

The other way around to achieve this is to implement a class which will be injected and thus add the code that we want to get executed on the class constructor.

We might believe that it is sufficient to implement a class which shall use the @Singleton annotation.

For example

@Singleton
class StartUpService {

    //The code that needs to be executed

}

But this will not work as expected since our component instances on play are created lazily when they are needed.

Instances are created lazily when they are needed. If a component is never used by another component, then it won’t be created at all. This is usually what you want. For most components there’s no point creating them until they’re needed. However, in some cases you want components to be started up straight away or even if they’re not used by another component. For example, you might want to send a message to a remote system or warm up a cache when the application starts. You can force a component to be created eagerly by using an eager binding.

To tackle this problem, our singleton has to be initialized eagerly. To achieve an eager initialization we will define an eager binding.

To define an eager binding we have to implement a class that extends the AbstractModule and then bind our service as an eager singleton.

package com.gkatzioura.eager

import com.google.inject.AbstractModule
import com.google.inject.name.Names

// A Module is needed to register bindings
class EagerLoaderModule extends AbstractModule {
  override def configure() = {

    bind(classOf[StartUpService]).asEagerSingleton
  }
}

Then we have to enable our module by declaring so to our conf/application.conf configuration.

play.modules.enabled += "com.gkatzioura.eager.EagerLoaderModule"

The above approach creates a module by defining it explicitly. The other approach is to use the default functionality where Play will load any class called Module that is defined in the root package.

In conclusion, play gives us the option to execute certain functions once the application has started. To do so we need to implement a component as an eager singleton. Skip the GlobalSettings as it is not advised by the official documentation.

Play and SBT basics

Previously we had an introduction to sbt, its default tasks and how to add extra tasks.

Play comes with the sbt console. The SBT console is a development console based on sbt that allows you to manage a Play application’s complete development cycle.

Let us create a play application using sbt and see the commands provided.

sbt new playframework/play-scala-seed.g8

[warn] Executing in batch mode.
[warn]   For better performance, hit [ENTER] to switch to interactive mode, or
[warn]   consider launching sbt without any commands, or explicitly passing 'shell'
[info] Set current project to development (in build file:/home/gkatzioura/Development/)

This template generates a Play Scala project 

name [play-scala-seed]: PlayExample
organization [com.example]: com.gkatzioura
scala_version [2.11.11]: 
play_version [2.5.14]: 
scalatestplusplay_version [2.0.0]: 

The result is a play project named playexample. By opening with an editor the project/plugins.sbt we can see the sbt plugin added to our project.
Therefore we are going to check what are the extra tasks that the sbt plugin provides and some tasks that can be generally helpful.

cd playexample; sbt 
[PlayExample] $ <tab><tab>
Display all 511 possibilities? (y or n)
...
h2-browser  
...                                                                                                                                                                                                                              
playStop                                           
playUpdateSecret     
playGenerateSecret                              
...
stage
...
  • playStop – Stop Play, if it has been started in non blocking mode
  • playGenerateSecret – This will generate a new secret that you can use in your application. For example the application secret can be used for Signing session cookies and CSRF tokens or
    built in encryption utilities
  • playUpdateSecret – Update the application conf to generate an application secret
  • stage – Create a local directory with all the files laid out as they would be in the final distribution.
  • h2-browser – Opens an h2 database browser. Pretty useful if you are using h2 for development

Those are some of the commands that you might use often. However if you want extra information, you can always type help play.

[PlayExample] $ help play

playExternalizeResources

  Whether resources should be externalized into the conf directory when Play is packaged as a distribution.

playCommonClassloader

  The common classloader, is ...
...

I’ve compiled a cheat sheet that lists some helpful sbt commands.
Sign up in the link to receive it.

SBT basics

Sbt is the de facto build tool in the Scala community.
Being used to other build tools you will be familiar with the commands

  • clean – Deletes files produced by the build, such as generated sources, compiled classes, and task caches.
  • compile – Compiles sources
  • test – Executes all tests
  • package – Produces the main artifact, such as a binary jar. This is typically an alias for the task that actually does the packaging.
  • help – Displays this help message or prints detailed help on requested commands (run ‘help ‘).
  • console – Starts the Scala interpreter with the project classes on the classpath.

Then we have extra commands suchs as

    • run – Runs a main class, passing along arguments provided on the command line.
    • tasks – Lists the tasks defined for the current project.
    • reload – (Re)loads the current project or changes to plugins project or returns from it.
    • console – Starts the Scala interpreter with the project classes on the classpath.

A key functionality is the new command.

For example by using new, we can create a project from the template specified (for example scala-seed.g8) using giter8.

sbt new scala/scala-seed.g8

...
Minimum Scala build. 

name [My Something Project]: hello

Template applied in ./hello

The previous snippet creates a project called hello.

The file build.sbt holds a sequence of key-value pairs called setting expressions. The left-hand side is a key and the right hand side is the body.
There are three types of keys.

  • SettingKey[T]: a key for a value computed once (the value is computed
    when loading the subproject, and kept around).
  • TaskKey[T]: a key for a value, called a task, that has to be recomputed
    each time, potentially with side effects.
  • InputKey[T]: a key for a task that has command line arguments as input.

For example if we want to add and extra task, to our previous project,  which prints hello, then we shall add the following lines to the build.sbt file.

import Dependencies._

lazy val hello = taskKey[Unit]("An example task")

lazy val root = (project in file(".")).
settings(
hello := { println("Hello!") },
inThisBuild(List(
organization := "com.example",
scalaVersion := "2.12.2",
version := "0.1.0-SNAPSHOT"
)),
name := "Hello",
libraryDependencies += scalaTest % Test
)

We can either run the task or ask for more info about the task.

>sbt
> hello
Hello!
[success] Total time: 0 s, completed May 1, 2017 6:08:36 PM
> help hello
An example task
> 

Depending on the project and the plugin used, there would be extra tasks and settings defined.

On the next post we will check play and sbt integration, and some basic commands.

I’ve compiled a cheat sheet that lists some helpful sbt commands.
Sign up in the link to receive it.