text,length,is_long_context,metric_val,label_metric
"== Step-by-step Cloud Foundry migration
=== Preview
https://docs.google.com/presentation/d/e/2PACX-1vSsEHn8cJfz8oWIwwUhdULt7nZzz3bBLK7OqM8UInkZ0LbQBCpPdhMoxsYGPe_90h9OvCu7dFlAimMJ/pub?start=false&loop=false&delayms=3000[Click here] to
check out the slides by https://twitter.com/ciberkleid[Cora Iberkleid] where she
migrates a setup of applications to be compliant with Spring Cloud Pipelines.
=== Introduction
This tutorial covers refactoring applications to comply with, and take advantage of, Spring Cloud Pipelines.
We will use a simple 3-tier application as an example:
image::{cf-migration-root-docs}/use_case_logical.png[title=""Use Case - Logical View""]
At the end of this tutorial, it will be possible to instantly create a Concourse pipeline for each app and run successfully through a full lifecycle, from source code commit to production deployment, following the lifecycle stages for testing and deployment recommended by Spring Cloud Pipelines. The app code bases will be improved with organized test coverage, a contract-based API, and a versioned database schema, enabling Spring Cloud Pipelines to carry out stubbed testing and to ensure backward compatibility for API and database schema changes.
=== Sample application - initial state
The sample application is implemented using Spring Boot apps for the UI and service tiers, and MySQL for the database.
The apps are built using Maven and pushed manually to Cloud Foundry. They leverage the three Pivotal Spring Cloud Services: Config Server, Service Discovery, and Circuit Breaker Dashboard. Rabbit is used to propagate Config Server refresh triggers.
The source code for the two Spring Boot apps is stored on GitHub, as is the backing repo for Config Server.
image::{cf-migration-root-docs}/use_case_implementation.png[title=""Use Case - Implementation""]
=== Sample application - end state
Through this tutorial, we will be adding Concourse and JFrog Bintray to manage the application lifecycle.
We will also be refactoring the application to comply with Spring Cloud Pipelines requirements and recommendations, including adding/organizing tests and introducing database versioning using Flyway and API contracts using Spring Cloud Contract.
=== Tutorial - toolset
* *GitHub* - sample app source code and config repositories, a sample stubrunner app repository, and the Spring Cloud Pipelines code base
- https://github.com/ciberkleid/greeting-ui[greeting-ui]
- https://github.com/ciberkleid/fortune-service[fortune-service]
- https://github.com/ciberkleid/app-config[app-config]
- https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot]
- https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines]
* *Pivotal Web Services* - public hosted Cloud Foundry offering http://run.pivotal.io[free trial accounts] and including MySQL, Rabbit, and Pivotal Spring Cloud Services in the Marketplace
* *Concourse*
* *JFrog Bintray* - public hosted Maven repository offering free https://bintray.com/signup/oss[OSS accounts]
* *Client Tools* - on your local machine, you will need an IDE as well as the mvn, git, cf, and fly (Concourse) CLIs
=== Tutorial - overview
The migration steps are broken down into three stages:
. *Scaffolding*
- Minimal refactoring to comply with basic Spring Cloud Pipelines requirements.
- At the end of this stage, each app will have a corresponding pipeline on Concourse. The pipelines will successfully build the apps, store the artifacts in Bintray, tag the GitHub repositories, and deploy the apps to Test, Stage, and Prod spaces in Cloud Foundry.
. *Tests*
- Add/organize tests to comply with Spring Cloud Pipelines recommendations. Incorporate flyway for database schema versioning and initial data loading.
- At the end of this stage, the pipelines will trigger unit and integration tests during the Build stage, smoke tests in the Test environment, and end-to-end tests in the Stage environment. The pipelines will also ensure backward compatibility for the database, such that you can safely roll back the backend service app, even after the database schema has been updated.
. *Contracts*
- Incorporate Spring Cloud Contract to define the API between the UI and service apps and auto-generate tests and stubs.
- At the end of this stage, the pipelines will catch breaking API changes during the Build stage and ensure backward compatibility for the API, such that you can safely roll back the backend service (producer) app, even after an API change.
=== Tutorial - step-by-step
==== Prep: Before you begin
If you want to simply review the migration steps explained below, you can look at the various branches in the https://github.com/ciberkleid/greeting-ui[greeting-ui] and https://github.com/ciberkleid/fortune-service[fortune-service] repositories - there is a branch representing the end-state of each stage:
image::{cf-migration-root-docs}/github_branches.png[title=""GitHub Branches""]
If you want to use this tutorial as a hands-on lab, fork each of the following repositories:
- https://github.com/ciberkleid/greeting-ui[greeting-ui]
- https://github.com/ciberkleid/fortune-service[fortune-service]
- https://github.com/ciberkleid/app-config[app-config]
Then, create a new directory on your local machine. You may name it anything you like; we will refer to it as `$SCP_HOME` throughout this tutorial.
In `$SCP_HOME`, clone your forks of `greeting-ui` and `fortune-service`, as well as the following two repositories:
- https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot]
- https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines]
Finally, create a directory called `$SCP_HOME/credentials`. Leave it empty for now.
==== Stage 1: Scaffolding
In this stage, we make minimal changes to satisfy basic Spring Cloud Pipelines requirements so that the apps can run through the entire pipeline without error. We make ""scaffolding"" changes only - no code changes.
The steps in this stage must be completed for both `greeting-ui` and `fortune-service`.
===== 1.1 Create GitHub branches
```bash
git branch version
git checkout -b sc-pipelines
```
Branch *version* is required to exist, though it can be created as an empty branch. It is used by Spring Coud Pipelines to generate a version number for each new pipeline execution.
Branch *sc-pipelines* is optional and can be named anything you wish. The intention is for you to use it as a working branch for the changes suggested in this tutorial (hence we create it and also check it out).
===== 1.2 Add Maven wrapper
```bash
mvn -N io.takari:maven:wrapper
```
This commands adds 4 files to a project:
[source,bash]
----
.
├── mvnw
├── mvnw.cmd
└── .mvn
└── wrapper
├── maven-wrapper.jar
└── maven-wrapper.properties
----
Make sure all four files are tracked by Git. For example, you can add the following to the `.gitignore` file:
```
#Exceptions
!/mvnw
!/mvnw.cmd
!/.mvn/wrapper/maven-wrapper.jar
!/.mvn/wrapper/maven-wrapper.properties
```
===== 1.3 Create Bintray maven repo package
We are using Bintray as the maven repository. Bintray requires that a package exist before any app artifacts can be uploaded.
Log into the Bintray UI and create the packages as follows. You can use the `Import from GitHub` option to create these:
image::{cf-migration-root-docs}/bintray_packages.png[title=""Bintray Packages""]
===== 1.4 Configure distribution management using Bintray maven repo
Edit the app `pom.xml` files as follows. Make sure the Bintray URLs match the URLs of the corresponding packages created in the previous step. The values you use will be different from the example shown below.
```xml
...
bintray
https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service
...
${distribution.management.release.id}
${distribution.management.release.url}
```
Though not required by Spring Cloud Pipelines, it makes sense to also configure your local maven settings with the credentials to your Bintray maven repo. To do so, edit your maven settings file, usually `~/.m2/settings.xml`. If the file does not exist, create it.
Note that the `id` must match the id specified in the previous step. Also, make sure to use your username and API token (not account password) instead of the sample values shown below.
```xml
bintray
ciberkleid
my-super-secret-api-token
```
===== 1.5 Push changes to GitHub
Push the above changes to GitHub. You should be pushing the following to each of the two app repos:
* 4 new maven wrapper files
* a modified .gitignore file
* a modified pom.xml
===== 1.6 Add Spring Cloud Pipelines credentials file
In `$SCP_HOME/credentials`, make two copies of the file `$SCP_HOME/spring-cloud-pipelines/concourse/credentials-sample-cf.yml`. Rename them as `credentials-fortune-service.yml` and `credentials-greeting-ui.yml`.
CAUTION: These files will contain credentials to your GitHub repo, your Bintray repo, and your Cloud Foundry foundation. Hence, we opt to put them in a separate directory. You may choose to store these files in a private git repo, but do not push them to a public repo.
Edit the git properties of each credentials file. Make sure to replace the sample values shown below as appropriate. For `tools-branch`, you may opt to use a fixed release (use v1.0.0.M8 or later for Cloud Foundry). Leave other values as they are, we will update those in later steps.
```yml
app-url: git@github.com:ciberkleid/fortune-service.git
app-branch: sc-pipelines
tools-scripts-url: https://github.com/spring-cloud/spring-cloud-pipelines.git
tools-branch: master
build-options: """"
github-private-key: |
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAvwkL97vBllOSE39Wa5ppczT1cr5Blmkhadfoa1Va2/IBVyvk
NJ9PqoTI+BahF2EgzweyiDSvKsstlTsG7QgiM9So8Voi2PlDOrXL6uOfCuAS/G8X
...
-----END RSA PRIVATE KEY-----
git-email: ciberkleid@pivotal.io
git-name: Cora Iberkleid
```
Edit the maven repo properties of each credentials file. Make sure to replace the sample values shown below as appropriate. Bintray requires separate URLs for uploads and downloads. If you are using a different artifact repository, such as Artifactory or Nexus, and the repository URL is the same for uploads and downloads, then you do not need to set `repo-with-binaries-for-upload`.
```yml
m2-settings-repo-id: bintray
m2-settings-repo-username: ciberkleid
m2-settings-repo-password: my-super-secret-api-token
repo-with-binaries: https://ciberkleid:my-super-secret-api-token@dl.bintray.com/ciberkleid/maven-repo
repo-with-binaries-for-upload: https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service
```
===== 1.7 Set Concourse pipeline
At this point, all of the build jobs, which run on Concourse workers, will succeed.
To verify this, log in to your Concourse target and set the Concourse pipelines. Update the target name in the example below as appropriate.
```bash
# Set greeting-ui pipeline
fly -t myTarget set-pipeline -p greeting-ui -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-greeting-ui.yml"" -n
# Set fortune-service pipeline
fly -t myTarget set-pipeline -p fortune-service -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-fortune-service.yml"" -n
```
Log into the Concourse UI and unpause the pipelines. Start each. You should see that the build jobs all succeed.
image::{cf-migration-root-docs}/concourse_build_success.png[title=""Build Success""]
In addition, you will see a new dev/ tag in each GitHub repo, as well as the app jars uploaded into Bintray.
The test, stage, and prod jobs will fail because we have not yet added scaffolding for deployment to Cloud Foundry. We will do that next.
===== 1.8 Add Cloud Foundry manifest
If you are deploying to Cloud Foundry, you may already be routinely including manifest files with your apps. Our sample apps did not have manifest files, so we add them now.
In the `greeting-ui` repo, create a `manifest.yml` file as follows:
```yml
---
applications:
- name: greeting-ui
timeout: 120
services:
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
In the `fortune-service` repo, create a `manifest.yml` file as follows:
```yml
---
applications:
- name: fortune-service
timeout: 120
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
The `TRUST_CERTS` variable is used by the Pivotal Spring Cloud Services (Config Server, Service Registry, and Circuit Breaker Dashboard), which we are using in this example. The value specified above assumes deployment to Pivotal Web Services. Update it accordingly if you are deploying to a different Cloud Foundry foundation, or you can leave it out altogether if you are replacing the Pivotal Spring Cloud Services with alternative implementations (e.g. deploying the services as apps and exposing them as user-provided services).
You may add additional values to the manifest files if you wish, for example if additional values are useful for any manual deployment you may still want to do, or desirable in your Spring Cloud Pipelines deployment. For example, an alternative manifest.yml for `fortune-service` could be as follows:
```yml
---
applications:
- name: fortune-service
timeout: 120
instances: 3
memory: 1024M
buildpack: https://github.com/cloudfoundry/java-buildpack.git
random-route: true
path: ./target/fortune-service-0.0.1-SNAPSHOT.jar
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
SPRING_PROFILES_ACTIVE: someProfile
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
Note that `random-route` and `path` are ignored by Spring Cloud Pipelines. `instances` is honored in stage and prod, but overridden with a value of 1 for test.
===== 1.9 Add Spring Cloud Pipelines manifest
The Cloud Foundry manifest created in the previous step includes the logical names of the services to which the apps should be bound, but it does describe how the services can be provisioned. Hence, we add a second manifest file so that Spring Cloud Pipelines can provision the services.
Add a file called `sc-pipelines.yml` to each app, and include the same list of services as in the corresponding `manifest.yml`. Add the necessary details such that Spring Cloud Pipelines can construct a `cf create-service` command.
NOTE: The `type: broker' parameter shown below instructs Spring Cloud Pipelines to provision a service using `cf create-service'. Other service types are also supported: cups, syslog, route, app, and stubrunner.
More specifically, for `greeting-ui`, create an `sc-pipelines.yml` file with the following content:
```yml
test:
services:
- name: config-server
type: broker
broker: p-config-server
plan: standard
params:
git:
uri: https://github.com/ciberkleid/app-config
useExisting: true
- name: cloud-bus
type: broker
broker: cloudamqp
plan: lemur
useExisting: true
- name: service-registry
type: broker
broker: p-service-registry
plan: standard
useExisting: true
- name: circuit-breaker-dashboard
type: broker
broker: p-circuit-breaker-dashboard
plan: standard
useExisting: true
```
The `sc-pipelines.yml` file for `fortune-service` is similar, with the addition of the `fortune-db` service:
```yml
test:
# list of required services
services:
- name: fortune-db
type: broker
broker: cleardb
plan: spark
useExisting: true
- name: config-server
type: broker
broker: p-config-server
plan: standard
params:
git:
uri: https://github.com/ciberkleid/app-config
useExisting: true
- name: cloud-bus
type: broker
broker: cloudamqp
plan: lemur
useExisting: true
- name: service-registry
type: broker
broker: p-service-registry
plan: standard
useExisting: true
- name: circuit-breaker-dashboard
type: broker
broker: p-circuit-breaker-dashboard
plan: standard
useExisting: true
```
The values above assume deployment to Pivotal Web Services. If you are deploying to a different Cloud Foundry foundation, please update the values accordingly. Also, make sure to replace the `config-server` uri with the address of your fork of the https://github.com/ciberkleid/app-config[app-config] repo.
TIP: Notice the `useExisting: true` parameter above. By default, Spring Cloud Pipelines will delete and recreate services in the `test` space. To override this behavior and re-use existing services, we set `useExisting: true`. This is helpful in cases where services may take time to provision and initialize, where there is no risk in re-using them between pipeline runs, or where it is desirable to retain the service instance from the last pipeline run (e.g. a database migration).
===== 1.10 Push changes to GitHub
Push the above changes to GitHub. You should be pushing the following to each of the two app repos:
* new app manifest file
* new sc-pipelines manifest file
===== 1.11 Create Cloud Foundry Orgs/Spaces
Spring Cloud Pipelines requires that the Cloud Foundry test, stage, and prod spaces exist before a pipeline is run. If you wish, you can use different foundations, orgs, and users for each. For simplicity, in this example, we use a single foundation (PWS), a single org, and a single user.
You can name the org(s) and spaces anything you like. Each app requires its own test space. The stage and prod spaces are shared.
For this example, create the following spaces:
```bash
cf create-space scp-test-greeting-ui
cf create-space scp-test-fortune-service
cf create-space scp-stage
cf create-space scp-prod
```
===== 1.12 Create Cloud Foundry stage and prod service instances
Spring Cloud Pipelines will dynamically create the services in the test spaces as per the `sc-pipelines.yml` file we created previously. Optionally, a second section can be added to the `sc-pipelines.yml` file for the stage environment, and these will be created dynamically as well. Prod services, however, must always be created manually.
For this example, we will create the stage and prod services manually.
Create the services listed in the app manifest files in both `scp-stage` and `scp-prod`.
===== 1.13 Update Spring Cloud Pipelines credentials file
Update the `greeting-ui` and `fortune-service` credentials files with Cloud Foundry information. Replace values in the example below as appropriate for your Cloud Foundry environment.
Notice that the test space name specified is a prefix, unlike the stage and prod space names, which are literals. Spring Cloud Pipelines will append the app name to the test space name, thereby matching the test space names we created manually. The stage and prod space names are not prefixes and will not be altered by Spring Cloud Pipelines.
Note also the `paas-hostname-uuid`. The value will be included in each route created. This value is optional, but it is useful in shared/multi-tenant environments such as PWS, as it helps ensure routes are unique. Change it to a unique uuid of your choosing.
```yml
pipeline-descriptor: sc-pipelines.yml
paas-type: cf
paas-hostname-uuid: cyi
# test values
paas-test-api-url: https://api.run.pivotal.io
paas-test-username: ciberkleid@pivotal.io
paas-test-password: secret
paas-test-org: S1Pdemo12
paas-test-space-prefix: scp-test
# stage values
paas-stage-api-url: https://api.run.pivotal.io
paas-stage-username: ciberkleid@pivotal.io
paas-stage-password: my-super-secret-password
paas-stage-org: S1Pdemo12
paas-stage-space: scp-stage
# prod values
paas-prod-api-url: https://api.run.pivotal.io
paas-prod-username: ciberkleid@pivotal.io
paas-prod-password: my-super-secret-password
paas-prod-org: S1Pdemo12
paas-prod-space: scp-prod
```
===== 1.14 Update Concourse pipeline with updated credentials files
Set the Concourse pipelines again, as we did previously, to update them with the values added to the credentials files. The test, stage, and prod jobs will all now succeed.
image::{cf-migration-root-docs}/concourse_test_stage_prod_success.png[title=""Test, Stage, & Prod Success""]
On Cloud Foundry, you will now see the apps deployed in the test, stage, and prod spaces. The image below shows the deployment of `fortune-service` to its dedicated test space. Notice that the 5 services declared in its manifest files (`sc-pipelines.yml` for provisioning, and `manifest.yml` for binding) have also been automatically provisioned. The image also shows the deployment of the same app to the shared prod space. Notice that the instance of the previous version has been renamed as *""venerable""* and stopped. If a rollback were deemed necessary, the `prod-rollback` job in the pipeline could be triggered to remove the currently running version, remove the `prod/` tag from GitHub, and re-start the former (*""venerable""*) version.
image::{cf-migration-root-docs}/cf_test_and_prod_deployed.png[title=""Cloud Foundry Test and Prod Deployment""]
===== Stage 1 Recap & next steps
What have we accomplished?
* By adding the basic scaffolding needed to enable Spring Cloud Pipelines to manage the lifecycle of `greeting-ui` and `fortune-service` from source code commit to production deploy, we have made it possible for the app dev teams to instantly and easily create pipelines for each app using a common, standardized template
* We can count on the pipelines to:
- automatically provision services in test spaces, and optionally in stage as well
- dynamically clean up the test spaces between pipeline executions
- upload the app artifacts to the maven repo (e.g. Bintray)
- tag the git repositories with `dev/` and `prod/`
* After each successful pipeline run, we are in a position to roll back to the last deployed version using the `prod-rollback` job, if necessary
These accomplishments are extremely valuable, but in order to derive confidence and reliability from the pipelines, we need to incorporate testing. We do this in Stage 2 of the app migration.
==== Stage 2: Tests
In this stage, we enable Spring Cloud Pipelines to execute tests so that we can increase confidence in the code being deployed. We do so by adding test profiles to the pom.xml files, and then organizing and/or adding tests in a way that corresponds to the profiles. By doing so, we are establishing standards around testing across development teams in the enterprise.
We will also enable database schema versioning in this stage, thereby providing the foundation for rollback testing during schema changes.
===== 2.1 Add Maven profiles
For both `greeting-ui` and `fortune-service`, add a `profiles` section to the `pom.xml` file, as shown below. Note that we are adding four profiles:
* default
** For unit and integration tests. Note that this profile includes all tests except those that will explicitly be called by the smoke and e2e profiles.
** Tests matching this profile will be executed during the build-and-upload job
* apicompatibility
** For ensuring backward compatibility in case of API changes. Note that this is not effective until Stage 3, when we will add contracts. However, we add this profile now to ensure the api-compatibility-check job does not execute other tests.
* smoke
** For tests to be run against the app deployed in the test space.
* e2e
** For tests to be run against the app deployed in the stage space.
```xml
default
true
org.apache.maven.plugins
maven-surefire-plugin
**/*Tests.java
**/*Test.java
**/smoke/**
**/e2e/**
org.springframework.boot
spring-boot-maven-plugin
apicompatibility
org.apache.maven.plugins
maven-surefire-plugin
**/contracttests/**/*Tests.java
**/contracttests/**/*Test.java
smoke
org.apache.maven.plugins
maven-surefire-plugin
smoke/**/*Tests.java
smoke/**/*Test.java
e2e
org.apache.maven.plugins
maven-surefire-plugin
e2e/**/*Tests.java
e2e/**/*Test.java
```
===== 2.2 Add/organize tests
Next, we ensure that we have a matching test package structure in our apps:
image::{cf-migration-root-docs}/test_package_structure.png[title=""Test Package Structure""]
Note that we are creating matching packages for the default, smoke, and e2e profiles only. We will address the package for the apicompatibility profile in Stage 3.
When working with your own apps, if you have existing tests, you would move the files into one of these packages now, and rename them so that they are included by the filters declared in the profiles (i.e. the file names end in `Test.java` or `Tests.java`)
In the case of our sample apps, there are no tests, so we add some now as follows.
*fortune-service default tests*
Add your unit and integration tests so that they match the default profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application running on the Concourse worker in the `build-and-upload` job.
As an example, we will add two tests, one that loads the context, and another that verifies the number of rows expected in the database:
```java
package io.pivotal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FortuneServiceApplication.class)
public class FortuneServiceApplicationTests {
@Test
public void contextLoads() throws Exception {
}
@Autowired
private JdbcTemplate template;
@Test
public void testDefaultSettings() throws Exception {
assertThat(this.template.queryForObject(""SELECT COUNT(*) from FORTUNE"",
Integer.class)).isEqualTo(7);
}
}
```
*fortune-service smoke tests*
Add your smoke tests so that they match the smoke profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-test-fortune-service` space. Two versions of these tests are executed against the app:
. the current version, in the `test-smoke` job
. the latest prod version, in the `test-rollback-smoke` job
image::{cf-migration-root-docs}/fortune_service_smoke_tests.png[title=""fortune-service Smoke Tests""]
In the test environment, we choose to verify that `fortune-service` is retrieving a fortune from `fortune-db`, and not returning its Hystrix fallback response:
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""The fortuneteller will be back soon."");
}
}
```
*fortune-service e2e tests*
Add your e2e tests so that they match the e2e profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `greeting-ui` is also present.
image::{cf-migration-root-docs}/fortune_service_e2e_tests.png[title=""fortune-service E2E Tests""]
In the e2e environment, we choose to use a string replacement to obtain the URL for `greeting-ui`. We also choose to verify that we are hitting `fortune-db` and not receiving Hystrix fallback responses from either application:
```java
package e2e;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = E2eTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class E2eTests {
// The app is running in CF but the tests are executed from Concourse worker,
// so the test will deduce the url to greeting-ui: it will assume the same host
// as fortune-service, and simply replace ""fortune-service"" with ""greeting-ui"" in the url
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl.replace(""fortune-service"", ""greeting-ui"") + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback responses from both fortune and greeting
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."").doesNotContain(""The fortuneteller will be back soon."");
}
}
```
*greeting-ui default tests*
Add your unit and integration tests so that they match the default profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application running on the Concourse worker in the `build-and-upload` job.
As an example, we will add one test that loads the context:
```java
package io.pivotal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GreetingUIApplication.class)
public class GreetingUIApplicationTests {
@Test
public void contextLoads() throws Exception {
}
}
```
*greeting-ui smoke tests*
Add your smoke tests so that they match the smoke profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-test-greeting-ui` space. Two versions of these tests are executed against the app:
. the current version, in the `test-smoke` job
. the latest prod version, in the `test-rollback-smoke` job
image::{cf-migration-root-docs}/greeting_ui_smoke_tests.png[title=""greeting-ui Smoke Tests""]
Since `fortune-service` is not deployed to the `scp-test-greeting-ui` space, we expect to receive the Hystrix fallback response defined in `greeting-ui`. Hence, our smoke test validates that condition:
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fallback_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Expect the hystrix fallback response
BDDAssertions.then(response.getBody()).contains(""This fortune is no good. Try another."");
}
}
```
*greeting-ui e2e tests*
Add your e2e tests so that they match the e2e profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `fortune-service` is also present.
image::{cf-migration-root-docs}/greeting_ui_e2e_tests.png[title=""greeting-ui E2E Tests""]
In the e2e environment, we choose to verify that we are hitting `fortune-service` and not receiving the Hystrix fallback response from `greeting-ui`:
```java
package e2e;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = E2eTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class E2eTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."");
}
}
```
===== 2.3 Enable database versioning
At this point we will also incorporate https://flywaydb.org/[Flyway], an OSS database migration tool, to track database schema versions and handle schema changes and data loading.
This change only needs to be made to `fortune-service`, since `fortune-service` owns the interaction with `fortune-db`.
*Add Flyway dependency*
We first add the Flyway dependency to the `fortune-service` `pom.xml`. We need not add a version as Spring Boot will take care of that for us.
```xml
org.flywaydb
flyway-core
```
*Create Flyway migration*
Next, we create a migration directory and our initial migration file following Flyway's file naming convention:
image::{cf-migration-root-docs}/fortune_service_flyway_file_name.png[title=""fortune-service Flyway File Name""]
Note the filename specifies the version (`V1`), followed by two underscore characters.
We place our CREATE TABLE and INSERT statements in our `src/main/resources/db/migration/V1__init.sql` file:
```sql
CREATE TABLE fortune (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
text varchar(255) not null
);
INSERT INTO fortune (text) VALUES ('Do what works.');
INSERT INTO fortune (text) VALUES ('Do the right thing.');
INSERT INTO fortune (text) VALUES ('Always be kind.');
INSERT INTO fortune (text) VALUES ('You learn from your mistakes... You will learn a lot today.');
INSERT INTO fortune (text) VALUES ('You can always find happiness at work on Friday.');
INSERT INTO fortune (text) VALUES ('You will be hungry again in one hour.');
INSERT INTO fortune (text) VALUES ('Today will be an awesome day!');
```
*Disable JPA DDL initialization*
Now that we are relying on Flyway to create and populate the schema, we need to disable JPA-based database initialization. We can set `ddl-auto` to `validate`, which will validate the schema against the application entities and throw an error in case of a mismatch, but not actually generate the schema:
```yml
spring:
jpa:
hibernate:
ddl-auto: validate
```
There are a few options for where to store the `ddl-auto` configuration, both in terms of location (in the `fortune-service` app or on the `app-config` GitHub repo) and in terms of file name. For this example, update the `application.yml` in the `fortune-service` app for local testing. Additionally, save these values in a new file called `application-flyway.yml` on your fork of https://github.com/ciberkleid/app-config[app-config].
By convention, `fortune-service` will pick up the configurations in `application-flyway.yml` if the string `flyway` is in the list of active Spring profiles. Thus, we add `flyway` to the environment variable `SPRING_PROFILES_ACTIVE` via the `fortune-service` `manifest.yml`:
```yml
---
applications:
- name: fortune-service
timeout: 120
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
SPRING_PROFILES_ACTIVE: flyway
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
*Remove non-Flyway data loading*
We can now remove the old code that populated the database. In our sample app, this was found in class `io.pivotal.FortuneServiceApplication`. The following shows the code we now remove:
```java
@Bean
CommandLineRunner loadDatabase(FortuneRepository fortuneRepo) {
return args -> {
// logger.debug(""loading database.."");
// fortuneRepo.save(new Fortune(1L, ""Do what works.""));
// fortuneRepo.save(new Fortune(2L, ""Do the right thing.""));
// fortuneRepo.save(new Fortune(3L, ""Always be kind.""));
// fortuneRepo.save(new Fortune(4L, ""You learn from your mistakes... You will learn a lot today.""));
// fortuneRepo.save(new Fortune(5L, ""You can always find happiness at work on Friday.""));
// fortuneRepo.save(new Fortune(6L, ""You will be hungry again in one hour.""));
// fortuneRepo.save(new Fortune(7L, ""Today will be an awesome day!""));
logger.debug(""record count: {}"", fortuneRepo.count());
fortuneRepo.findAll().forEach(x -> logger.debug(x.toString()));
};
}
```
We also no longer need the Fortune entity constructors, so we can comment these out in class `io.pivotal.fortune.Fortune` as shown below:
```java
// public Fortune() {
// }
//
// public Fortune(Long id, String text) {
// super();
// this.id = id;
// this.text = text;
// }
```
*Flyway integration summary*
With that, we have completed the setup for Flyway and our database schema is now versioned. From this point onward, Spring Boot will call `Flyway.migrate()` to perform the database migration. As long as we follow Flyway conventions for future schema changes, Flyway will take care of tracking the schema version and migrating the database for us.
From a rollback perspective, Spring Cloud Pipelines includes two jobs in the `test` phase - `test-rollback-deploy` and `test-rollback-smoke` - wherein it validates that the latest prod jar works against the newly updated database. The purpose is to ensure that we can roll back the application in prod if a problem is discovered after the prod database schema has been updated, and avoid the burden of rolling back the database.
Read more about https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-use-a-higher-level-database-migration-tool[Spring Boot database initialization with Flyway] for further information, including Flyway configuration options.
===== 2.4 Push changes to GitHub
For `greeting-ui`, you should be pushing the following new or modified files:
* pom.xml
* src/test/java/e2e/E2eTests.java
* src/test/java/io/pivotal/GreetingUIApplicationTests.java
* src/test/java/smoke/SmokeTests.java
For `fortune-service`, you should be pushing the following new or modified files:
* pom.xml
* src/test/java/e2e/E2eTests.java
* src/test/java/io/pivotal/FortuneServiceApplicationTests.java
* src/test/java/smoke/SmokeTests.java
* src/main/resources/db/migration/V1__init.sql
* src/main/resources/application.yml
* manifest.yml
* src/main/java/io/pivotal/FortuneServiceApplication.java
* src/main/java/io/pivotal/fortune/Fortune.java
For `app-config`, you should be pushing the following new or modified files:
* application-flyway.yml
===== 2.5 Re-run the pipelines
Run through the pipelines again and view the output for the jobs that run the default, smoke, and e2e tests. You will see that the tests we added in this stage were executed.
As you run through the pipelines a second time, you will see the smoke tests from the latest prod version run against the database in the `test-rollback-smoke` job. In this case there is no schema upgrade, but nonetheless the tests confirm that the latest prod version of the app can be used with the current database schema.
You can see the database version information stored in the database by Flyway either by querying the database itself or by hitting the flyway endpoint on the `fortune-service` URL. Here is an example from the scp-stage environment:
image::{cf-migration-root-docs}/fortune_service_flyway_schema_info.png[title=""fortune-service Flyway Schema Info""]
===== Stage 2 Recap & next steps
What have we accomplished?
* By integrating our applications with the testing strategy built into Spring Cloud Pipelines, we have increased the effectiveness of the pipelines, as well as our confidence in them
* Established a standard approach to organizing tests that will bring consistency within and across development teams
* Enabled auto-managed database versioning and backward compatibility testing that will alleviate database schema management throughout the release management lifecycle
We are now positioned to add any unit, integration, smoke, and end-to-end tests to our code base and extract a very high level of reliability and confidence from our pipelines. We are also better positioned to ensure that our dev teams conform to these practices, given the structure established by Spring Cloud Pipelines and the fast feedback and visibility we gain from the pipelines as they execute the tests.
However, we could benefit further by incorporating contracts to define and test the API integration points between applications. We do this in Stage 3 of the app migration.
==== Stage 3: Contracts
In this stage, we introduce contract-based programming practices into our sample application. Doing so improves API management capabilities, including defining, communicating, and testing API semantics. It also enables us to catch breaking API changes (i.e. validate API backward compatibility) in the build phase. This will extend the effectiveness of the pipelines, encourage better communication and programming practices across development teams, and provide faster feedback to developers.
We will integrate Spring Cloud Contract and add contracts, stubs, and a stub runner. We will also now complete and make use of the apicompatibility profile defined in Stage 2.
===== 3.1 Create a contract
Let's start by creating the contract for the interaction between `greeting-ui` and `fortune-service`. The contract should describe the following expectation:
* `greeting-ui` makes a `GET` request to the root URL of `fortune-service` and expects a response with status 200 and a string (""foo fortune"") in the body
We codify this using groovy syntax as follows:
```groovy
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description(""""""
should return a fortune string
"""""")
request {
method GET()
url ""/""
}
response {
status 200
body ""foo fortune""
}
}
```
Save this contract in the `fortune-service` code base in the following location, which is compliant with Spring Cloud Contract convention (`src/test/resources/contracts//`):
image::{cf-migration-root-docs}/fortune_service_contract_file.png[title=""fortune-service Flyway Contract File""]
NOTE: You can optionally enable your IDE to assist with contract syntax by adding the Spring Cloud Contract Verifier to your `pom.xml` file. It is pluggable, and includes groovy and pact by default.
```xml
org.springframework.cloud
spring-cloud-starter-contract-verifier
test
```
===== 3.2 Create a base class for contract tests
Now that we have a codified contract, we want to enable auto-generation of contract-based tests. The auto-generation, which we will configure in the next steps, requires a base class that stubs out the service that satisfies the API call, so that we can run the test without external dependencies (e.g. the DB). The objective is to focus on testing API semantics.
We create the base class in the `fortune-service` test package as follows:
```java
package io.pivotal.fortune;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.mockito.BDDMockito;
public class BaseClass {
@Before
public void setup() {
FortuneService service = BDDMockito.mock(FortuneService.class);
BDDMockito.given(service.getFortune()).willReturn(""foo fortune"");
RestAssuredMockMvc.standaloneSetup(new FortuneController(service));
}
}
```
===== 3.3 Enable automated contract-based testing
Now that we have a contract and a base class, we can use the *Spring Cloud Contract maven plugin* to auto-generate contract tests, stubs, and a stub jar.
First we add the Spring Cloud Contract version to the list of properties in the `fortune-service` `pom.xml` file, since we will reference it when we enable the Spring Cloud Contract maven plugin:
```xml
...
1.2.1.RELEASE
...
```
Next, we edit the `default` profile in the `fortune-service` `pom.xml` file as follows:
* Add a plugin block for Spring Cloud Contract maven plugin
* Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests
* Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests`
Note that the package of the contracttests will be included by the `include` filter in the `default` profile, so these tests will be run against the app during the `build-and-upload` job. For `fortune-service`, this serves to validate that the app conforms to the contract.
Here is the complete profile:
```xml
default
true
org.apache.maven.plugins
maven-surefire-plugin
**/*Tests.java
**/*Test.java
**/smoke/**
**/e2e/**
org.springframework.boot
spring-boot-maven-plugin
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
io.pivotal.fortune.BaseClass
io.pivotal.fortune.contracttests
```
When the app is built, the Spring Cloud Contract maven plugin will also now produce a stub and a stub jar containing the contract and stub. This stub jar will be uploaded to Bintray, along with the usual app jar. As we will see shortly, this stub jar can be used by the `greeting-ui` dev team while they wait for `fortune-service` to be completed. In other words, this gives the `greeting-ui` dev team a producer to test against that is based on a mutually agreed-upon contract without the lead time of having to wait for `fortune-service` to implement anything more than a base class, and without having to manually stub out calls to `fortune-service` based on arbitrary or static responses.
TIP: Package the project locally (run `mvn package`) to observe the tests, stubs, and stub jar that the Spring Cloud Contract maven plugin generates. See the image below for reference.
image::{cf-migration-root-docs}/fortune_service_generated_tests.png[title=""Generated Tests and Stubs""]
===== 3.4 Enable backward compatibility API check
To enable Spring Cloud Pipelines to catch any breaking API changes during the `build-api-compatibility-check` job, we add the Spring Cloud Contract maven plugin to the `apicompatibility` profile as well.
In this case, we want the plugin to generate tests based on contracts outside of the project (the ones from the latest prod version), so we configure the plugin to download the latest prod stub jar, which contains the old contract. The plugin will use the old contract and the specified base class, which in our example is the same as the one in the previous step, to generate contract tests. These tests are run against the new code to validate that it is still compatible with consumers complying with the prior contract. This ensures backward compatibility for the API.
In short, we edit the apicompatibility profile in the `fortune-service` `pom.xml` file as follows:
* Add a plugin block for Spring Cloud Contract maven plugin
* Configure it to download the latest prod stub jar from Bintray to obtain the old contract
* Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests (we are using the same one as in the prior step)
* Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests`
Note that the package of the contracttests matches the `include` filter in the `apicompatibility` profile, so these tests will be run against the app during the `build-api-compatibility-check` job. For `fortune-service`, this serves to validate that the app conforms to the old contract.
Here is the complete profile:
```xml
apicompatibility
org.apache.maven.plugins
maven-surefire-plugin
**/contracttests/**/*Tests.java
**/contracttests/**/*Test.java
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
${repo.with.binaries}
${project.groupId}
${project.artifactId}
stubs
${latest.production.version}
/
io.pivotal.fortune.BaseClass
io.pivotal.fortune.contracttests
```
The values for `${repo.with.binaries}` and `${latest.production.version}` will be injected dynamically by Spring Cloud Pipelines. You can run this locally by providing these values manually as system properties in the maven command.
===== 3.5 Push changes to GitHub
All changes in Stage 3 thus far are in `fortune-service`. At this point, you should be pushing the following new or modified files:
* pom.xml
* src/test/resources/contracts/greeting-ui/shouldReturnAFortune.groovy
* src/test/java/io/pivotal/fortune/BaseClass.java
===== 3.6 Re-run the fortune-service pipeline
Run through the `fortune-service` pipeline to generate stubs. The following output from the `build-and-upload` job shows the auto-generation of tests and stubs:
image::{cf-migration-root-docs}/fortune_service_build_and_upload_test_and_stub_generation.png[title=""fortune-service build-and-upload Test and Stub Generation""]
You will also see output in the `build-and-upload` job showing the execution of these tests against the code.
Additionally, you will see the stub jar uploaded to Bintray along with the usual app jar.
Finally, as you run through the pipeline a second time, you will see the contract tests from the latest prod version run against the new code in the output of the `build-api-compatibility-check` job. In this case there is no API change, but nonetheless the tests confirm that the latest prod version of the API can be used with the current code base.
===== 3.7 Enable stubs for integration tests
We are in the home stretch! Let's turn our attention to `greeting-ui`.
The following image compares the path of a request through `greeting-ui` in the build phase, both with and without stubs.
image::{cf-migration-root-docs}/greeting_ui_build_flow.png[title=""greeting-ui Build Flow""]
Without stubs, we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. In this case, the stubs are loaded into the `greeting-ui` process. This leads us to our next task: load the stubs produced by `fortune-service`.
*Enable in-process stub runner*
To load the stubs into the `greeting-ui` process, we must enable the Spring Cloud Contract Stub Runner dependency. This dependency will start an in-process stub runner that automatically configures Wiremock.
Add the following to the `greeting-ui` `pom.xml` file:
```xml
org.springframework.cloud
spring-cloud-starter-contract-stub-runner
test
```
*Add integration tests aligned with the contract*
Next, we add integration tests to `greeting-ui` that test for the expected response declared in the contract.
Add the following class to the test package in `greeting-ui`:
```java
package io.pivotal.fortune;
import io.pivotal.GreetingUIApplication;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GreetingUIApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE,
properties = {""spring.application.name=greeting-ui"", ""spring.cloud.circuit.breaker.enabled=false"", ""hystrix.stream.queue.enabled=false""})
@AutoConfigureStubRunner(ids = {""io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION""},
repositoryRoot = ""${REPO_WITH_BINARIES}""
//workOffline = true
)
public class FortuneServiceTests {
@Autowired FortuneService fortuneService;
@Test
public void shouldSendRequestToFortune() {
// when
String fortune = fortuneService.getFortune();
// then
BDDAssertions.then(fortune).isEqualTo(""foo fortune"");
}
}
```
At this point, we can get through the build phase for `greeting-ui`, and the integration tests will be executed against the `fortune-service` stubs running in the `greeting-ui` process on the Concourse worker.
TIP: Notice the configuration of `@AutoConfigureStubRunner` - you can replace the version with a `+` sign if using Artifactory or Nexus and it will automatically choose the latest available version on the maven repo.
TIP: Setting `workOffline=true` (commented out but shown for informational purposes above) would make the stub runner get the stubs from the local maven repo. This is useful for local testing. Alternatively, set the `$REPO_WITH_BINARIES` environment variable to the value used in the credentials file before doing a local maven build, and the local build will download the stubs from your remote maven repo (e.g. Bintray).
===== 3.8 Enable stubs for smoke tests
The following image compares the path of a request through `greeting-ui` in the test phase, both with and without stubs. Note that in the build phase, where the app process is running on the Concourse worker, we ran the stubs in the same process. In the test environment (Cloud Foundry), we will run the stubs in a separate process using a standalone stub runner application.
image::{cf-migration-root-docs}/greeting_ui_test_flow.png[title=""greeting-ui Test Flow""]
As in the build phase, without stubs we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract.
We will rely on Spring Cloud Pipelines to:
* Deploy a stub runner application
* Provide the stub runner application the necessary information to download the stubs
* Open a port on the stub runner application for each stub
We will rely on the stub runner application to:
* Download the stubs from our maven repo (Bintray)
* Expose each stub on a separate port
* Register each stub in the Service Discovery server
The following steps describe how to configure this.
*Provide standalone stub runner app jar*
In the Prep step for this tutorial, you cloned the https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] repo to your local machine. The next step is to build this app and upload it to Bintray to make the jar available to Spring Cloud Pipelines.
As mentioned in Stage 1 of this tutorial, Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create a package for `cloudfoundry-stub-runner-boot`. If you forked this repo, you can use the `Import from GitHub` option. Otherwise, create the package manually and choose any license (e.g. Apache 2.0).
Now you are ready to build and upload this app to Bintray. The following script shows cloning, building and uploading. Edit as appropriate to match your Bintray URL, the Bintray ID in your `~/.m2/settings/xml` file, and the `cloudfoundry-stub-runner-boot` repo URL if you chose to fork it.
```bash
# Edit to match your Bintray URL and M2 repo ID setting (check your ~/.m2/settings.xml file)
MAVEN_REPO_URL=https://api.bintray.com/maven/ciberkleid/maven-repo/cloudfoundry-stub-runner-boot
MAVEN_REPO_ID=bintray
# Clone cloudfoundry-stub-runner-boot
git clone https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot.git
cd cloudfoundry-stub-runner-boot
# Build and upload
./mvnw clean deploy -Ddistribution.management.release.url=""${MAVEN_REPO_URL}"" -Ddistribution.management.release.id=""${MAVEN_REPO_ID}""
```
You should now see the `cloudfoundry-stub-runner-boot` artifacts uploaded on Bintray.
*Provide standalone stub runner app manifest*
Next, we add a manifest file for the stub runner app for deployment to Cloud Foundry.
We will place this file in the `greeting-ui` repo. The file name and location can be your choice. For this example, we will use `sc-pipelines/manifest-stubrunner.yml`:
image::{cf-migration-root-docs}/greeting_ui_stubrunner_manifest.png[title=""greeting-ui Stub Runner Manifest""]
We populate this `manifest-stubrunner.yml` with the content shown below so that the stub runner binds to `service-registry`. The stub runner will register the `fortune-service` stub there so that `greeting-ui` can discover it in the same way it will discover the actual `fortune-service` app endpoint in stage and prod. From the `greeting-ui` perspective, there is no difference in how it interacts with Eureka and the stub runner app in test and the way it will interact with Eureka and the `fortune-service` app in stage and prod.
```yml
---
applications:
- name: stubrunner
timeout: 120
services:
- service-registry
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
*Provide stub runner jar and manifest info to the pipeline*
Now that we have a jar file and manifest file for our stub runner app, we need to provide this information to our `greeting-ui` pipeline so that the pipeline downloads the jar from Bintray and deploys it to Cloud Foundry. We do this through the `greeting-ui` `sc-pipelines.yml` file. We add an entry to the list of services in the `test` section, as follows:
```yml
- name: stubrunner
type: stubrunner
coordinates: io.pivotal:cloudfoundry-stub-runner-boot:0.0.1.M1
pathToManifest: sc-pipelines/manifest-stubrunner.yml
```
Notice that `name` matches the name of the app in `manifest-stubrunner.yml`, `coordinates` corresponds to the jar coordinates on the maven repo, and `pathToManifest` matches our chosen fie name for the stub runner app manifest.
Note also the `type` is set to `stubrunner`, which Spring Cloud Pipelines will recognize as a stanalone stub runner app and treat accordingly.
*Provide stub configuration for stub runner app*
The final steps in the configuration of the standalone stub runner app are:
* Enable the stub runner app to download the `fortune-service` stub from Bintray
* Open a second port on the container to receive requests for this stub
To accomplish this, we put stub and port configuration information into the properties section of the `greeting-ui` `pom.xml` file, using a property called `stubrunner.ids`. This property can accept a list of stubrunner ids, but for this tutorial, we only have one:
```xml
...
io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION:stubs:10000
```
Spring Cloud Pipelines will use this information in two ways:
. It will provide this information to the stub runner app via the app's environment variables
- Spring Cloud Pipelines will aslo provide the `$REPO_WITH_BINARIES` as an env var for the stub runner app
- The stub runner app will use this information to download the stub from Bintray and expose it on the specified port
. It will open the additional port specified on the stub runner app and map a new route to it
- The format for each route will be `----.`
- In our example, this would be `stubrunner-cyi-test-greeting-ui-10000.cfapps.io`
Since we bound our stub runner app to `service-registry` (Eureka), the stub runner app will register the stub URL under the application name `FORTUNE-SERVICE` on Eureka:
image::{cf-migration-root-docs}/greeting_ui_stub_runner_eureka_registration.png[title=""greeting-ui Stub Runner Eureka Registration""]
This completes the process of configuring the standalone stub runner application.
NOTE: The port configuration may be automated by Spring Cloud Pipelines in the future, such that it will not be necessary to include the port in the `stubrunner.ids`, but for the moment, we are required to specify the port each stub should use.
*Edit smoke tests to align with the contract*
Finally, we edit our smoke tests for `greeting-ui` to ensure the response does *not* contain the hystrix fallback, since we are now expecting a response from the stub.
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."");
}
}
```
In this case, in contrast to the integration test we created earlier for `greeting-ui`, we do not include `@AutoConfigureStubRunner` since we are using a standalone stub runner application.
===== 3.9 Push changes to GitHub
Push contract-based changes for `greeting-ui`. You should be pushing the following new or modified files:
* pom.xml
* sc-pipelines.yml
* sc-pipelines/manifest-stubrunner.yml
* src/test/java/io/pivotal/fortune/FortuneServiceTests.java
* src/test/java/smoke/SmokeTests.java
At this point, we can run through the full pipeline for `greeting-ui` and leverage the contract-based stub in both the build and test environments.
===== Stage 3 Recap
What have we accomplished?
By implementing a contract-driven approach with auto-generation of tests and stubs, we have introduced a clean, structured, and reliable way to define, communicate, document, manage and test APIs
* Inter-team communication will be simpler
- Consumer and producer teams can now communicate requirements through codified contracts
- The inventory of contracts serves as a record and reference of the agreed upon APIs
* Developer productivity will increase
- Producers can quickly and easily generate contract-based stubs
- Consumers no longer have to manually stub out APIs and write tests with arbitrary hard-coded responses - instead they can use the auto-generated stubs and test for contract-based responses
- Both producers and consumers can validate they are compliant with the contract
- Producers can verify backward compatibility of API changes
- Troubleshooting will be easier
- Failure and feedback will be faster
=== Conclusion
This concludes the tutorial on migrating apps for Spring Cloud Pipelines for Cloud Foundry.
Moving forward, the refactoring work needed here can be incorporated into your and/or your team's standard practices. In short:
*Good:*
* Use maven or gradle wrappers
* Include a Cloud Foundry manifest file in your app repo
* Include a pipeline descriptor (`sc-manifest.yml`) in your app repo
* Create an empty `version` branch in your app repo
* Include artifact repository configuration in the pom.xml file
* Align your Cloud Foundry spaces with Spring Cloud Pipelines model (isolated test space, shared stage and prod spaces)
*Better*
* Include default, apicompatibility, smoke, and e2e profiles in the pom.xml file
* Organize tests accordingly in your app repo
*Best*
* Use a database migration tool like flyway
* Use contract-based API programming
Implementing all the *""good""* practices above already positions you to instantly create pipelines for your apps usign Spring Cloud Pipelines. This is a huge win in terms of consistency and productivity, and standardization across development teams. Of course, this is an open source project, so it can be modified to meet your needs.
Implementing the *""better""* practices will ensure the proper tests get run at the proper time. At that point you can add as much test coverage as you need to have high confidence in your pipelines.
Implementing the *""best""* practices will give you additional confidence in your pipeline and encourage better programming practices for database version and API management across development teams. It will also give you higher confidence in your pipelines and enable you to avoid the cumbersome business of rolling back a database.
Happy coding!
",16253,True,2814.784687227654,median
"== Step-by-step Cloud Foundry migration
=== Preview
https://docs.google.com/presentation/d/e/2PACX-1vSsEHn8cJfz8oWIwwUhdULt7nZzz3bBLK7OqM8UInkZ0LbQBCpPdhMoxsYGPe_90h9OvCu7dFlAimMJ/pub?start=false&loop=false&delayms=3000[Click here] to
check out the slides by https://twitter.com/ciberkleid[Cora Iberkleid] where she
migrates a setup of applications to be compliant with Spring Cloud Pipelines.
=== Introduction
This tutorial covers refactoring applications to comply with, and take advantage of, Spring Cloud Pipelines.
We will use a simple 3-tier application as an example:
image::{cf-migration-root-docs}/use_case_logical.png[title=""Use Case - Logical View""]
At the end of this tutorial, it will be possible to instantly create a Concourse pipeline for each app and run successfully through a full lifecycle, from source code commit to production deployment, following the lifecycle stages for testing and deployment recommended by Spring Cloud Pipelines. The app code bases will be improved with organized test coverage, a contract-based API, and a versioned database schema, enabling Spring Cloud Pipelines to carry out stubbed testing and to ensure backward compatibility for API and database schema changes.
=== Sample application - initial state
The sample application is implemented using Spring Boot apps for the UI and service tiers, and MySQL for the database.
The apps are built using Maven and pushed manually to Cloud Foundry. They leverage the three Pivotal Spring Cloud Services: Config Server, Service Discovery, and Circuit Breaker Dashboard. Rabbit is used to propagate Config Server refresh triggers.
The source code for the two Spring Boot apps is stored on GitHub, as is the backing repo for Config Server.
image::{cf-migration-root-docs}/use_case_implementation.png[title=""Use Case - Implementation""]
=== Sample application - end state
Through this tutorial, we will be adding Concourse and JFrog Bintray to manage the application lifecycle.
We will also be refactoring the application to comply with Spring Cloud Pipelines requirements and recommendations, including adding/organizing tests and introducing database versioning using Flyway and API contracts using Spring Cloud Contract.
=== Tutorial - toolset
* *GitHub* - sample app source code and config repositories, a sample stubrunner app repository, and the Spring Cloud Pipelines code base
- https://github.com/ciberkleid/greeting-ui[greeting-ui]
- https://github.com/ciberkleid/fortune-service[fortune-service]
- https://github.com/ciberkleid/app-config[app-config]
- https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot]
- https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines]
* *Pivotal Web Services* - public hosted Cloud Foundry offering http://run.pivotal.io[free trial accounts] and including MySQL, Rabbit, and Pivotal Spring Cloud Services in the Marketplace
* *Concourse*
* *JFrog Bintray* - public hosted Maven repository offering free https://bintray.com/signup/oss[OSS accounts]
* *Client Tools* - on your local machine, you will need an IDE as well as the mvn, git, cf, and fly (Concourse) CLIs
=== Tutorial - overview
The migration steps are broken down into three stages:
. *Scaffolding*
- Minimal refactoring to comply with basic Spring Cloud Pipelines requirements.
- At the end of this stage, each app will have a corresponding pipeline on Concourse. The pipelines will successfully build the apps, store the artifacts in Bintray, tag the GitHub repositories, and deploy the apps to Test, Stage, and Prod spaces in Cloud Foundry.
. *Tests*
- Add/organize tests to comply with Spring Cloud Pipelines recommendations. Incorporate flyway for database schema versioning and initial data loading.
- At the end of this stage, the pipelines will trigger unit and integration tests during the Build stage, smoke tests in the Test environment, and end-to-end tests in the Stage environment. The pipelines will also ensure backward compatibility for the database, such that you can safely roll back the backend service app, even after the database schema has been updated.
. *Contracts*
- Incorporate Spring Cloud Contract to define the API between the UI and service apps and auto-generate tests and stubs.
- At the end of this stage, the pipelines will catch breaking API changes during the Build stage and ensure backward compatibility for the API, such that you can safely roll back the backend service (producer) app, even after an API change.
=== Tutorial - step-by-step
==== Prep: Before you begin
If you want to simply review the migration steps explained below, you can look at the various branches in the https://github.com/ciberkleid/greeting-ui[greeting-ui] and https://github.com/ciberkleid/fortune-service[fortune-service] repositories - there is a branch representing the end-state of each stage:
image::{cf-migration-root-docs}/github_branches.png[title=""GitHub Branches""]
If you want to use this tutorial as a hands-on lab, fork each of the following repositories:
- https://github.com/ciberkleid/greeting-ui[greeting-ui]
- https://github.com/ciberkleid/fortune-service[fortune-service]
- https://github.com/ciberkleid/app-config[app-config]
Then, create a new directory on your local machine. You may name it anything you like; we will refer to it as `$SCP_HOME` throughout this tutorial.
In `$SCP_HOME`, clone your forks of `greeting-ui` and `fortune-service`, as well as the following two repositories:
- https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot]
- https://github.com/spring-cloud/spring-cloud-pipelines[spring-cloud-pipelines]
Finally, create a directory called `$SCP_HOME/credentials`. Leave it empty for now.
==== Stage 1: Scaffolding
In this stage, we make minimal changes to satisfy basic Spring Cloud Pipelines requirements so that the apps can run through the entire pipeline without error. We make ""scaffolding"" changes only - no code changes.
The steps in this stage must be completed for both `greeting-ui` and `fortune-service`.
===== 1.1 Create GitHub branches
```bash
git branch version
git checkout -b sc-pipelines
```
Branch *version* is required to exist, though it can be created as an empty branch. It is used by Spring Coud Pipelines to generate a version number for each new pipeline execution.
Branch *sc-pipelines* is optional and can be named anything you wish. The intention is for you to use it as a working branch for the changes suggested in this tutorial (hence we create it and also check it out).
===== 1.2 Add Maven wrapper
```bash
mvn -N io.takari:maven:wrapper
```
This commands adds 4 files to a project:
[source,bash]
----
.
├── mvnw
├── mvnw.cmd
└── .mvn
└── wrapper
├── maven-wrapper.jar
└── maven-wrapper.properties
----
Make sure all four files are tracked by Git. For example, you can add the following to the `.gitignore` file:
```
#Exceptions
!/mvnw
!/mvnw.cmd
!/.mvn/wrapper/maven-wrapper.jar
!/.mvn/wrapper/maven-wrapper.properties
```
===== 1.3 Create Bintray maven repo package
We are using Bintray as the maven repository. Bintray requires that a package exist before any app artifacts can be uploaded.
Log into the Bintray UI and create the packages as follows. You can use the `Import from GitHub` option to create these:
image::{cf-migration-root-docs}/bintray_packages.png[title=""Bintray Packages""]
===== 1.4 Configure distribution management using Bintray maven repo
Edit the app `pom.xml` files as follows. Make sure the Bintray URLs match the URLs of the corresponding packages created in the previous step. The values you use will be different from the example shown below.
```xml
...
bintray
https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service
...
${distribution.management.release.id}
${distribution.management.release.url}
```
Though not required by Spring Cloud Pipelines, it makes sense to also configure your local maven settings with the credentials to your Bintray maven repo. To do so, edit your maven settings file, usually `~/.m2/settings.xml`. If the file does not exist, create it.
Note that the `id` must match the id specified in the previous step. Also, make sure to use your username and API token (not account password) instead of the sample values shown below.
```xml
bintray
ciberkleid
my-super-secret-api-token
```
===== 1.5 Push changes to GitHub
Push the above changes to GitHub. You should be pushing the following to each of the two app repos:
* 4 new maven wrapper files
* a modified .gitignore file
* a modified pom.xml
===== 1.6 Add Spring Cloud Pipelines credentials file
In `$SCP_HOME/credentials`, make two copies of the file `$SCP_HOME/spring-cloud-pipelines/concourse/credentials-sample-cf.yml`. Rename them as `credentials-fortune-service.yml` and `credentials-greeting-ui.yml`.
CAUTION: These files will contain credentials to you GitHub repo, your Bintray repo, and your Cloud Foundry foundation. Hence, we opt to put them in a separate directory. You may choose to store these files in a private git repo, but do not push them to a public repo.
Edit the git properties of each credentials file. Make sure to replace the sample values shown below as appropriate. For `tools-branch`, you may opt to use a fixed release (use v1.0.0.M8 or later for Cloud Foundry). Leave other values as they are, we will update those in later steps.
```yml
app-url: git@github.com:ciberkleid/fortune-service.git
app-branch: sc-pipelines
tools-scripts-url: https://github.com/spring-cloud/spring-cloud-pipelines.git
tools-branch: master
build-options: """"
github-private-key: |
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAvwkL97vBllOSE39Wa5ppczT1cr5Blmkhadfoa1Va2/IBVyvk
NJ9PqoTI+BahF2EgzweyiDSvKsstlTsG7QgiM9So8Voi2PlDOrXL6uOfCuAS/G8X
...
-----END RSA PRIVATE KEY-----
git-email: ciberkleid@pivotal.io
git-name: Cora Iberkleid
```
Edit the maven repo properties of each credentials file. Make sure to replace the sample values shown below as appropriate. Bintray requires separate URLs for uploads and downloads. If you are using a different artifact repository, such as Artifactory or Nexus, and the repository URL is the same for uploads and downloads, then you do not need to set `repo-with-binaries-for-upload`.
```yml
m2-settings-repo-id: bintray
m2-settings-repo-username: ciberkleid
m2-settings-repo-password: my-super-secret-api-token
repo-with-binaries: https://ciberkleid@my-super-secret-api-token@dl.bintray.com/ciberkleid/maven-repo
repo-with-binaries-for-upload: https://api.bintray.com/maven/ciberkleid/maven-repo/fortune-service
```
===== 1.7 Set Concourse pipeline
At this point, all of the build jobs, which run on Concourse workers, will succeed.
To verify this, log in to your Concourse target and set the Concourse pipelines. Update the target name in the example below as appropriate.
```bash
# Set greeting-ui pipeline
fly -t myTarget set-pipeline -p greeting-ui -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-greeting-ui.yml"" -n
# Set fortune-service pipeline
fly -t myTarget set-pipeline -p fortune-service -c ""${SCP_HOME}/spring-cloud-pipelines/concourse/pipeline.yml"" -l ""${SCP_HOME}/credentials/credentials-fortune-service.yml"" -n
```
Log into the Concourse UI and unpause the pipelines. Start each. You should see that the build jobs all succeed.
image::{cf-migration-root-docs}/concourse_build_success.png[title=""Build Success""]
In addition, you will see a new dev/ tag in each GitHub repo, as well as the app jars uploaded into Bintray.
The test, stage, and prod jobs will fail because we have not yet added scaffolding for deployment to Cloud Foundry. We will do that next.
===== 1.8 Add Cloud Foundry manifest
If you are deploying to Cloud Foundry, you may already be routinely including manifest files with your apps. Our sample apps did not have manifest files, so we add them now.
In the `greeting-ui` repo, create a `manifest.yml` file as follows:
```yml
---
applications:
- name: greeting-ui
timeout: 120
services:
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
In the `fortune-service` repo, create a `manifest.yml` file as follows:
```yml
---
applications:
- name: fortune-service
timeout: 120
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
The `TRUST_CERTS` variable is used by the Pivotal Spring Cloud Services (Config Server, Service Registry, and Circuit Breaker Dashboard), which we are using in this example. The value specified above assumes deployment to Pivotal Web Services. Update it accordingly if you are deploying to a different Cloud Foundry foundation, or you can leave it out altogether if you are replacing the Pivotal Spring Cloud Services with alternative implementations (e.g. deploying apps and exposing them as user-provided services).
You may add additional values to the manifest files if you wish, for example if additional values are useful for any manual deployment you may still want to do, or desirable in your Spring Cloud Pipelines deployment. For example, an alternative manifest.yml for `fortune-service` could be as follows:
```yml
---
applications:
- name: fortune-service
timeout: 120
instances: 3
memory: 1024M
buildpack: https://github.com/cloudfoundry/java-buildpack.git
random-route: true
path: ./target/fortune-service-0.0.1-SNAPSHOT.jar
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
SPRING_PROFILES_ACTIVE: someProfile
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
Note that `random-route` and `path` are ignored by Spring Cloud Pipelines. `instances` is honored in stage and prod, but overridden with a value of 1 for test.
===== 1.9 Add Spring Cloud Pipelines manifest
The Cloud Foundry manifest created in the previous step includes the logical names of the services to which the apps should be bound, but it does describe how the services can be provisioned. Hence, we add a second manifest file so that Spring Cloud Pipelines can provision the services.
Add a file called `sc-pipelines.yml` to each app, and include the same list of services as in the corresponding `manifest.yml`. Add the necessary details such that Spring Cloud Pipelines can construct a `cf create-service` command.
NOTE: The `type: broker' parameter shown below instructs Spring Cloud Pipelines to provision a service using `cf create-service'. Other service types are also supported: cups, syslog, route, app, and stubrunner.
More specifically, for `greeting-ui`, create an `sc-pipelines.yml` file with the following content:
```yml
test:
services:
- name: config-server
type: broker
broker: p-config-server
plan: standard
params:
git:
uri: https://github.com/ciberkleid/app-config
useExisting: true
- name: cloud-bus
type: broker
broker: cloudamqp
plan: lemur
useExisting: true
- name: service-registry
type: broker
broker: p-service-registry
plan: standard
useExisting: true
- name: circuit-breaker-dashboard
type: broker
broker: p-circuit-breaker-dashboard
plan: standard
useExisting: true
```
The `sc-pipelines.yml` file for `fortune-service` is similar, with the addition of the `fortune-db` service:
```yml
test:
# list of required services
services:
- name: fortune-db
type: broker
broker: cleardb
plan: spark
useExisting: true
- name: config-server
type: broker
broker: p-config-server
plan: standard
params:
git:
uri: https://github.com/ciberkleid/app-config
useExisting: true
- name: cloud-bus
type: broker
broker: cloudamqp
plan: lemur
useExisting: true
- name: service-registry
type: broker
broker: p-service-registry
plan: standard
useExisting: true
- name: circuit-breaker-dashboard
type: broker
broker: p-circuit-breaker-dashboard
plan: standard
useExisting: true
```
The values above assume deployment to Pivotal Web Services. If you are deploying to a different Cloud Foundry foundation, please update the values accordingly. Also, make sure to replace the `config-server` uri with the address of your fork of the https://github.com/ciberkleid/app-config[app-config] repo.
TIP: Notice the `useExisting: true` parameter above. By default, Spring Cloud Pipelines will delete and recreate services in the `test` space. To override this behavior and re-use existing services, we set `useExisting: true`. This is helpful in cases where services may take time to provision and initialize, where there is no risk in re-using them between pipeline runs, or where it is desirable to retain the service instance from the last pipeline run (e.g. a database migration).
===== 1.10 Push changes to GitHub
Push the above changes to GitHub. You should be pushing the following to each of the two app repos:
* new app manifest file
* new sc-pipelines manifest file
===== 1.11 Create Cloud Foundry Orgs/Spaces
Spring Cloud Pipelines requires that the Cloud Foundry test, stage, and prod spaces exist before a pipeline is run. If you wish, you can use different foundations, orgs, and users for each. For simplicity, in this example, we use a single foundation (PWS), a single org, and a single user.
You can name the org(s) and spaces anything you like. Each app requires its own test space. The stage and prod spaces are shared.
For this example, create the following spaces:
```bash
cf create-space scp-test-greeting-ui
cf create-space scp-test-fortune-service
cf create-space scp-stage
cf create-space scp-prod
```
===== 1.12 Create Cloud Foundry stage and prod service instances
Spring Cloud Pipelines will dynamically create the services in the test spaces as per the `sc-pipelines.yml` file we created previously. Optionally, a second section can be added to the `sc-pipelines.yml` file for the stage environment, and these will be created dynamically as well. Prod services, however, must always be created manually.
For this example, we will create the stage and services manually.
Create the services listed in the app manifest files in both `scp-stage` and `scp-prod`.
===== 1.13 Update Spring Cloud Pipelines credentials file
Update the `greeting-ui` and `fortune-service` credentials files with Cloud Foundry information. Replace values in the example below as appropriate for your Cloud Foundry environment.
Notice that the space name specified is a prefix. Spring Cloud Pipelines will append the app name, matching the test space names created previously. The stage and prod space names are not prefixes and will not be altered by Spring Cloud Pipelines.
Note also the `paas-hostname-uuid`. The value will be included in each route created. This value is optional, but it is useful in shared/multi-tenant environments such as PWS, as it helps ensure routes are unique. Change it to a unique uuid of your choosing.
```yml
pipeline-descriptor: sc-pipelines.yml
paas-type: cf
paas-hostname-uuid: cyi
# test values
paas-test-api-url: https://api.run.pivotal.io
paas-test-username: ciberkleid@pivotal.io
paas-test-password: secret
paas-test-org: S1Pdemo12
paas-test-space-prefix: scp-test
# stage values
paas-stage-api-url: https://api.run.pivotal.io
paas-stage-username: ciberkleid@pivotal.io
paas-stage-password: my-super-secret-password
paas-stage-org: S1Pdemo12
paas-stage-space: scp-stage
# prod values
paas-prod-api-url: https://api.run.pivotal.io
paas-prod-username: ciberkleid@pivotal.io
paas-prod-password: my-super-secret-password
paas-prod-org: S1Pdemo12
paas-prod-space: scp-prod
```
===== 1.14 Update Concourse pipeline with updated credentials files
Set the Concourse pipelines again, as we did previously, to update them with the values added to the credentials files. The test, stage, and prod jobs will all now succeed.
image::{cf-migration-root-docs}/concourse_test_stage_prod_success.png[title=""Test, Stage, & Prod Success""]
On Cloud Foundry, you will now see the apps deployed in the test, stage, and prod spaces. The image below shows the deploymnet of `fortune-service` to its isolated and dedicated test space, with the 5 services declared in its manifest files (`sc-pipelines.yml` for provisioning, and `manifest.yml` for binding). It also shows the deployment of the same app to the shared prod space, including the stopped instance of the previous version. If a rollback were deemed necessary, the `prod-rollback` job in the pipeline could be triggered to remove the currently running version, remove the `prod/` tag from GitHub, and re-start the former (*""venerable""*) version.
image::{cf-migration-root-docs}/cf_test_and_prod_deployed.png[title=""Cloud Foundry Test and Prod Deployment""]
===== Stage 1 Recap & next steps
What have we accomplished?
* By adding the basic scaffolding needed to enable Spring Cloud Pipelines to manage the lifecycle of `greeting-ui` and `fortune-service` from source code commit to production deploy, we have made it possible for the app dev teams to instantly and easily create pipelines for each app using a common, standardized template
* We can count on the pipelines to:
- automatically provision services in test spaces, and optionally in stage as well
- dynamically clean up the test spaces between pipeline executions
- upload the app artifacts to the maven repo (Bintray)
- tag the GitHub repositories with `dev/` and `prod/`
* After each successful pipeline run, we are in a position to roll back to the last deployed version using the `prod-rollback` job, if necessary
These accomplishments are extremely valuable, but in order to derive confidence and reliability from the pipelines, we need to incorporate testing. We do this in Stage 2 of the app migration.
==== Stage 2: Tests
In this stage, we enable Spring Cloud Pipelines to execute tests so that we can increase confidence in the code being deployed. We do so by adding test profiles to the pom.xml files, and then organizing and/or adding tests in a way that corresponds to the profiles. By doing so, we are establishing standards around testing across development teams in the enterprise.
We will also enable database schema versioning in this stage, thereby providing the foundation for rollback testing during schema changes.
===== 2.1 Add Maven profiles
For both `greeting-ui` and `fortune-service`, add a `profiles` section to the `pom.xml` file, as shown below. Note that we are adding four profiles:
* default
** For unit and integration tests. Note that this profile includes all tests except those that will explicitly be called by the smoke and e2e profiles.
** Tests matching this profile will be executed during the build-and-upload job
* apicompatibility
** For ensuring backward compatibility in case of API changes. Note that this is not effective until Stage 3, when we will add contracts. However, we add this profile now to ensure the api-compatibility-check job does not execute other tests.
* smoke
** For tests to be run against the app deployed in the test space.
* e2e
** For tests to be run against the app deployed in the stage space.
```xml
default
true
org.apache.maven.plugins
maven-surefire-plugin
**/*Tests.java
**/*Test.java
**/smoke/**
**/e2e/**
org.springframework.boot
spring-boot-maven-plugin
apicompatibility
org.apache.maven.plugins
maven-surefire-plugin
**/contracttests/**/*Tests.java
**/contracttests/**/*Test.java
smoke
org.apache.maven.plugins
maven-surefire-plugin
smoke/**/*Tests.java
smoke/**/*Test.java
e2e
org.apache.maven.plugins
maven-surefire-plugin
e2e/**/*Tests.java
e2e/**/*Test.java
```
===== 2.2 Add/organize tests
Next, we ensure that we have a matching test package structure in our apps:
image::{cf-migration-root-docs}/test_package_structure.png[title=""Test Package Structure""]
Note that we are creating matching packages for the default, smoke, and e2e profiles only. We will address the package for the apicompatibility profile in Stage 3.
When working with your own apps, if you have existing tests, you would now move them into one of these packages now, and rename them so that they are included in the filters declared in the profiles (i.e. the file names end in `Test.java` or `Tests.java`)
In the case of our sample apps, there are no tests, so we add some now as follows.
*fortune-service default tests*
Add your unit and integration tests so that they match the default profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application running on the Concourse worker in the `build-and-upload` job.
As an example, we will add two tests, one that loads the context, and another that verifies the number of rows expected in the database:
```java
package io.pivotal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FortuneServiceApplication.class)
public class FortuneServiceApplicationTests {
@Test
public void contextLoads() throws Exception {
}
@Autowired
private JdbcTemplate template;
@Test
public void testDefaultSettings() throws Exception {
assertThat(this.template.queryForObject(""SELECT COUNT(*) from FORTUNE"",
Integer.class)).isEqualTo(7);
}
}
```
*fortune-service smoke tests*
Add your smoke tests so that they match the smoke profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-test-fortune-service` space. Two versions of these tests are executed against the app:
. the current version, in the `test-smoke` job
. the latest prod version, in the `test-rollback-smoke` job
image::{cf-migration-root-docs}/fortune_service_smoke_tests.png[title=""fortune-service Smoke Tests""]
In the test environment, we choose to verify that `fortune-service` is retrieving a fortune from `fortune-db`, and not returning its Hystrix fallback response:
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""The fortuneteller will be back soon."");
}
}
```
*fortune-service e2e tests*
Add your e2e tests so that they match the e2e profile as defined in the `fortune-service` `pom.xml` file. These will be executed on Concourse against the `fortune-service` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `greeting-ui` is also present.
image::{cf-migration-root-docs}/fortune_service_e2e_tests.png[title=""fortune-service E2E Tests""]
In the e2e environment, we choose to use a string replacement to obtain the URL for `greeting-ui`. We also choose to verify that we are hitting `fortune-db` and not receiving Hystrix fallback responses from either application:
```java
package e2e;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = E2eTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class E2eTests {
// The app is running in CF but the tests are executed from Concourse worker,
// so the test will deduce the url to greeting-ui: it will assume the same host
// as fortune-service, and simply replace ""fortune-service"" with ""greeting-ui"" in the url
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl.replace(""fortune-service"", ""greeting-ui"") + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback responses from both fortune and greeting
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."").doesNotContain(""The fortuneteller will be back soon."");
}
}
```
*greeting-ui default tests*
Add your unit and integration tests so that they match the default profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application running on the Concourse worker in the `build-and-upload` job.
As an example, we will add one test that loads the context:
```java
package io.pivotal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GreetingUIApplication.class)
public class GreetingUIApplicationTests {
@Test
public void contextLoads() throws Exception {
}
}
```
*greeting-ui smoke tests*
Add your smoke tests so that they match the smoke profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-test-greeting-ui` space. Two versions of these tests are executed against the app:
. the current version, in the `test-smoke` job
. the latest prod version, in the `test-rollback-smoke` job
image::{cf-migration-root-docs}/greeting_ui_smoke_tests.png[title=""greeting-ui Smoke Tests""]
Since `fortune-service` is not deployed to the `scp-test-greeting-ui` space, we expect to receive the Hystrix fallback response defined in `greeting-ui`. Hence, our smoke test validates that condition:
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fallback_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Expect the hystrix fallback response
BDDAssertions.then(response.getBody()).contains(""This fortune is no good. Try another."");
}
}
```
*greeting-ui e2e tests*
Add your e2e tests so that they match the e2e profile as defined in the `greeting-ui` `pom.xml` file. These will be executed on Concourse against the `greeting-ui` application deployed in the Cloud Foundry `scp-stage` space. This space is shared, so we assume `fortune-service` is also present.
image::{cf-migration-root-docs}/greeting_ui_e2e_tests.png[title=""greeting-ui E2E Tests""]
In the e2e environment, we choose to verify that we are hitting `fortune-service` and not receiving the Hystrix fallback response from `greeting-ui`:
```java
package e2e;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = E2eTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class E2eTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."");
}
}
```
===== 2.3 Enable database versioning
At this point will also incorporate https://flywaydb.org/[Flyway], an OSS database migration tool, to track database schema versions and handle schema changes and data loading.
This change only needs to be made to `fortune-service`, since `fortune-service` owns the interaction with `fortune-db`.
*Add Flyway dependency*
We first add the Flyway dependency to the `fortune-service` `pom.xml`. We need not add a version as Spring Boot will take care of that for us.
```xml
org.flywaydb
flyway-core
```
*Create Flyway migration*
Next, we create a migration directory and our initial migration file following Flyway's file naming convention:
image::{cf-migration-root-docs}/fortune_service_flyway_file_name.png[title=""fortune-service Flyway File Name""]
Note the filename specifies the version (`V1`), followed by two underscore characters.
We place our CREATE TABLE and INSERT statements in our `src/main/resources/db/migration/V1__init.sql` file:
```sql
CREATE TABLE fortune (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
text varchar(255) not null
);
INSERT INTO fortune (text) VALUES ('Do what works.');
INSERT INTO fortune (text) VALUES ('Do the right thing.');
INSERT INTO fortune (text) VALUES ('Always be kind.');
INSERT INTO fortune (text) VALUES ('You learn from your mistakes... You will learn a lot today.');
INSERT INTO fortune (text) VALUES ('You can always find happiness at work on Friday.');
INSERT INTO fortune (text) VALUES ('You will be hungry again in one hour.');
INSERT INTO fortune (text) VALUES ('Today will be an awesome day!');
```
*Disable JPA DDL initialization*
Now that we are relying on Flyway to create and populate the schema, we need to disable JPA-based database initialization. We can set `ddl-auto` to `validate`, which will validate the schema against the application entities and throw an error in case of a mismatch, but not actually generate the schema:
```yml
spring:
jpa:
hibernate:
ddl-auto: validate
```
There are a few options for where to store the `ddl-auto` configuration, both in terms of location (in the `fortune-service` app or on the `app-config` GitHub repo) and in terms of file name. For this example, update the `application.yml` in the `fortune-service` app for local testing. additionally, save these values in a new file called `application-flyway.yml` on your fork of https://github.com/ciberkleid/app-config[app-config].
By convention, `fortune-service` will pick up the configurations in `application-flyway.yml` if the string `flyway` is in the list of active Spring profiles. Thus, we add `flyway` to the environment variable `SPRING_PROFILES_ACTIVE` via the `fortune-service` `manifest.yml`:
```yml
---
applications:
- name: fortune-service
timeout: 120
services:
- fortune-db
- config-server
- cloud-bus
- service-registry
- circuit-breaker-dashboard
env:
SPRING_PROFILES_ACTIVE: flyway
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
*Remove non-Flyway data loading*
We can now remove the old code that populated the database. In our sample app, this was found in class `io.pivotal.FortuneServiceApplication`. The following shows the code we now remove:
```java
@Bean
CommandLineRunner loadDatabase(FortuneRepository fortuneRepo) {
return args -> {
// logger.debug(""loading database.."");
// fortuneRepo.save(new Fortune(1L, ""Do what works.""));
// fortuneRepo.save(new Fortune(2L, ""Do the right thing.""));
// fortuneRepo.save(new Fortune(3L, ""Always be kind.""));
// fortuneRepo.save(new Fortune(4L, ""You learn from your mistakes... You will learn a lot today.""));
// fortuneRepo.save(new Fortune(5L, ""You can always find happiness at work on Friday.""));
// fortuneRepo.save(new Fortune(6L, ""You will be hungry again in one hour.""));
// fortuneRepo.save(new Fortune(7L, ""Today will be an awesome day!""));
logger.debug(""record count: {}"", fortuneRepo.count());
fortuneRepo.findAll().forEach(x -> logger.debug(x.toString()));
};
}
```
We also no longer need the Fortune entity constructors, so we can comment these out in class `io.pivotal.fortune.Fortune` as shown below:
```java
// public Fortune() {
// }
//
// public Fortune(Long id, String text) {
// super();
// this.id = id;
// this.text = text;
// }
```
*Flyway integration summary*
With that, we have completed the setup for Flyway and our database schema is now versioned. From this point onward, Spring Boot will call `Flyway.migrate()` to perform the database migration. As long as we follow Flyway conventions for future schema changes, Flyway will take care of tracking the schema version and migrating the database for us.
From a rollback perspective, Spring Cloud Pipelines includes two jobs in the `test` phase - `test-rollback-deploy` and `test-rollback-smoke` - wherein it validates that the latest prod jar works against the newly updated database. The purpose is to ensure that we can roll back the application in prod if a problem is discovered after the prod database schema has been updated, and avoid the burden of rolling back the database.
Read more about https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-use-a-higher-level-database-migration-tool[Spring Boot database initialization with Flyway] for further information, including Flyway configuration options.
===== 2.4 Push changes to GitHub
For `greeting-ui`, you should be pushing the following new or modified files:
* pom.xml
* src/test/java/e2e/E2eTests.java
* src/test/java/io/pivotal/GreetingUIApplicationTests.java
* src/test/java/smoke/SmokeTests.java
For `fortune-service`, you should be pushing the following new or modified files:
* pom.xml
* src/test/java/e2e/E2eTests.java
* src/test/java/io/pivotal/FortuneServiceApplicationTests.java
* src/test/java/smoke/SmokeTests.java
* src/main/resources/db/migration/V1__init.sql
* src/main/resources/application.yml
* manifest.yml
* src/main/java/io/pivotal/FortuneServiceApplication.java
* src/main/java/io/pivotal/fortune/Fortune.java
For `app-config`, you should be pushing the following new or modified files:
* application-flyway.yml
===== 2.5 Re-run the pipelines
Run through the pipelines again and view the output for the jobs that run the default, smoke, and e2e tests. You will see that the tests we added in this stage were executed.
As you run through the pipelines a second time, you will see the smoke tests from the latest prod version run against the database in the `test-rollback-smoke` job. In this case there is no schema upgrade, but nonetheless the tests confirm that the latest prod version of the app can be used with the current database schema.
You can see the database version information stored in the database by Flyway either by querying the database itself or by hitting the flyway endpoint on the `fortune-service` URL. Here is an example from the scp-stage environment:
image::{cf-migration-root-docs}/fortune_service_flyway_schema_info.png[title=""fortune-service Flyway Schema Info""]
===== Stage 2 Recap & next steps
What have we accomplished?
* By integrating our applications with the testing strategy built into Spring Cloud Pipelines, we have increased the effectiveness of the pipelines, as well as our confidence in them
* Established a standard approach to organizing tests that will bring consistency within and across development teams
* Enabled auto-managed database versioning and backward compatibility testing that will alleviate database schema management throughout the release management lifecycle
We are now positioned to add any unit, integration, smoke, and end-to-end tests to our code base and extract a very high level of reliability and confidence from our pipelines. We are also better positioned to ensure that our dev teams conform to these practices, given the structure imposed by Spring Cloud Pipelines and the fast feedback and visibility we gain from the pipelines as they execute the tests.
However, we could benefit further by incorporating contracts to define and test the API integration points between applications. We do this in Stage 3 of the app migration.
==== Stage 3: Contracts
In this stage, we introduce contract-based programming practices into our sample application. Doing so improves API management capabilities, including defining, communicating, and testing API semantics. It also enables us to catch breaking API changes (i.e. validate API backward compatibility) in the build phase. This will extend the effectiveness of the pipelines, encourage better communication and programming practices across development teams, and provide faster feedback to developers.
We will integrate Spring Cloud Contract and add contracts, stubs, and a stub runner. We will also now complete and make use of the apicompatibility profile defined in Stage 2.
===== 3.1 Create a contract
Let's start by creating the contract for the interaction between `greeting-ui` and `fortune-service`. The contract should describe the following expectation:
* `greeting-ui` makes a `GET` request to the root URL of `fortune-service` and expects a response with status 200 and a string (""foo fortune"") in the body
We codify this using groovy syntax as follows:
```groovy
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description(""""""
should return a fortune string
"""""")
request {
method GET()
url ""/""
}
response {
status 200
body ""foo fortune""
}
}
```
Save this contract in the `fortune-service` code base in the following location, which is compliant with Spring Cloud Contract convention (`src/test/resources/contracts//`):
image::{cf-migration-root-docs}/fortune_service_contract_file.png[title=""fortune-service Flyway Contract File""]
NOTE: You can optionally enable your IDE to assist with contract syntax by adding the Spring Cloud Contract Verifier to your `pom.xml` file. It is pluggable, and includes groovy and pact by default.
```xml
org.springframework.cloud
spring-cloud-starter-contract-verifier
test
```
===== 3.2 Create a base class for contract tests
Now that we have a codified contract, we want to enable auto-generation of contract-based tests. The auto-generation, which we will configure in the next steps, requires a base class that stubs out the service that satisfies the API call, so that we can run the test without external dependencies (e.g. the DB). The objective is to focus on testing API semantics.
We create the base class in the `fortune-service` test package as follows:
```java
package io.pivotal.fortune;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.mockito.BDDMockito;
public class BaseClass {
@Before
public void setup() {
FortuneService service = BDDMockito.mock(FortuneService.class);
BDDMockito.given(service.getFortune()).willReturn(""foo fortune"");
RestAssuredMockMvc.standaloneSetup(new FortuneController(service));
}
}
```
===== 3.3 Enable automated contract-based testing
Now that we have a contract and a base class, we can use the *Spring Cloud Contract maven plugin* to auto-generate contract tests, stubs, and a stub jar.
First we add the Spring Cloud Contract version to the list of properties in the `fortune-service` `pom.xml` file, since we will reference it when we enable the Spring Cloud Contract maven plugin:
```xml
...
1.2.1.RELEASE
...
```
Next, we edit the `default` profile in the `fortune-service` `pom.xml` file as follows:
* Add a plugin block for Spring Cloud Contract maven plugin
* Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests
* Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests`
Note that the package of the contracttests will be included by the `include` filter in the `default` profile, so these tests will be run against the app during the `build-and-upload` job. For `fortune-service`, this serves to validate that the app conforms to the contract.
Here is the complete profile:
```xml
default
true
org.apache.maven.plugins
maven-surefire-plugin
**/*Tests.java
**/*Test.java
**/smoke/**
**/e2e/**
org.springframework.boot
spring-boot-maven-plugin
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
io.pivotal.fortune.BaseClass
io.pivotal.fortune.contracttests
```
When the app is built, the Spring Cloud Contract maven plugin will also now produce a stub and a stub jar containing the contract and stub. This stub jar will be uploaded to Bintray, along with the usual app jar. As we will see shortly, this stub jar can be used by the `greeting-ui` dev team while they wait for `fortune-service` to be completed. Note that this gives the `greeting-ui` dev team a producer to test against that is based on a mutually agreed-upon contract without the lead time of having to wait for `fortune-service` to implement anything more than a base class, and without having to manually stub out calls to `fortune-service` based on arbitrary or static responses.
TIP: Package the project locally (run `mvn package`) to observe the tests, stubs, and stub jar that the Spring Cloud Contract maven plugin generates. See the image below for reference.
image::{cf-migration-root-docs}/fortune_service_generated_tests.png[title=""Generated Tests and Stubs""]
===== 3.4 Enable backward compatibility API check
To enable Spring Cloud Pipelines to catch any breaking API changes during the `build-api-compatibility-check` job, we add the Spring Cloud Contract maven plugin to the `apicompatibility` profile as well.
In this case, we want the plugin to generate tests based on contracts outside of the project (the ones from the latest prod version), so we configure the plugin to download the latest prod stub jar, which contains the old contract. The plugin will use the old contract and the specified base class, which in our example is the same as the one in the previous step, to generate contract tests. These tests are run against the new code to validate that it is still compatible with consumers complying with the prior contract. This ensures backward compatibility for the API.
In short, we edit the apicompatibility profile in the `fortune-service` `pom.xml` file as follows:
* Add a plugin block for Spring Cloud Contract maven plugin
* Configure it to download the latest prod stub jar from Bintray to obtain the old contract
* Configure it to use our base class (`io.pivotal.fortune.BaseClass`) to generate tests (we are using the same one as in the prrior step)
* Configure it to place auto-generated tests in the test package `io.pivotal.fortune.contracttests`
Note that the package of the contracttests matches the `include` filter in the `apicompatibility` profile, so these tests will be run against the app during the `build-api-compatibility-check` job. For `fortune-service`, this serves to validate that the app conforms to the old contract.
Here is the complete profile:
```xml
apicompatibility
org.apache.maven.plugins
maven-surefire-plugin
**/contracttests/**/*Tests.java
**/contracttests/**/*Test.java
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
${repo.with.binaries}
${project.groupId}
${project.artifactId}
stubs
${latest.production.version}
/
io.pivotal.fortune.BaseClass
io.pivotal.fortune.contracttests
```
The values for `${repo.with.binaries}` and `${latest.production.version}` will be injected dynamically by Spring Cloud Pipelines. You can run this locally by providing these values manually as system properties in the maven command.
===== 3.5 Push changes to GitHub
All changes in Stage 3 thus far are in `fortune-service`. At this point, you should be pushing the following new or modified files:
* pom.xml
* src/test/resources/contracts/greeting-ui/shouldReturnAFortune.groovy
* src/test/java/io/pivotal/fortune/BaseClass.java
===== 3.6 Re-run the fortune-service pipeline
Run through the `fortune-service` pipeline to generate stubs. The following output from the `build-and-upload` job shows the auto-generation of tests and stubs:
image::{cf-migration-root-docs}/fortune_service_build_and_upload_test_and_stub_generation.png[title=""fortune-service build-and-upload Test and Stub Generation""]
You will also see output in the `build-and-upload` job showing the execution of these tests against the code.
Additionally, you will see the stub jar uploaded to Bintray along with the usual app jar.
Finally, as you run through the pipeline a second time, you will see the contract tests from the latest prod version run against the new code in the output of the `build-api-compatibility-check` job. In this case there is no API change, but nonetheless the tests confirm that the latest prod version of the API can be used with the current code base.
===== 3.7 Enable stubs for integration tests
We are in the home stretch! Let's turn our attention to `greeting-ui`.
The following image compares the path of a request through `greeting-ui` in the build phase, both with and without stubs.
image::{cf-migration-root-docs}/greeting_ui_build_flow.png[title=""greeting-ui Build Flow""]
Without stubs, we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract. In this case, the stubs are loaded into the `greeting-ui` process. This leads us to our next task: load the stubs produced by `fortune-service`.
*Enable in-process stub runner*
To load the stubs into the `greeting-ui` process, we must enable the Spring Cloud Contract Stub Runner dependency. This dependency will start an in-process stub runner that automatically configures Wiremock.
Add the following to the `greeting-ui` `pom.xml` file:
```xml
org.springframework.cloud
spring-cloud-starter-contract-stub-runner
test
```
*Add integration tests aligned with the contract*
Next, we add integration tests to `greeting-ui` that test for the expected response declared in the contract.
Add the following class to the test package in `greeting-ui`:
```java
package io.pivotal.fortune;
import io.pivotal.GreetingUIApplication;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GreetingUIApplication.class, webEnvironment = SpringBootTest.WebEnvironment.NONE,
properties = {""spring.application.name=greeting-ui"", ""spring.cloud.circuit.breaker.enabled=false"", ""hystrix.stream.queue.enabled=false""})
@AutoConfigureStubRunner(ids = {""io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION""},
repositoryRoot = ""${REPO_WITH_BINARIES}""
//workOffline = true
)
public class FortuneServiceTests {
@Autowired FortuneService fortuneService;
@Test
public void shouldSendRequestToFortune() {
// when
String fortune = fortuneService.getFortune();
// then
BDDAssertions.then(fortune).isEqualTo(""foo fortune"");
}
}
```
At this point, we can get through the build phase for `greeting-ui`, and the integration tests will be executed against the `fortune-service` stubs running in the `greeting-ui` process on the Concourse worker.
TIP: Notice the configuration of `@AutoConfigureStubRunner` - you can replace the version with a `+` sign if using Artifactory or Nexus and it will automatically choose the latest available version on the maven repo.
TIP: Setting `workOffline=true` (commented out but shown for informational purposes above) would make the stub runner get the stubs from the local maven repo. This is useful for local testing. Alternatively, set the `$REPO_WITH_BINARIES` environment variable to the value used in the credentials file before doing a local maven build, and the local build will download the stubs from your remote maven repo (e.g. Bintray).
===== 3.8 Enable stubs for smoke tests
The following image compares the path of a request through `greeting-ui` in the test phase, both with and without stubs. Note that in the build phase, where the app process is running on the Concourse worker, we ran the stubs in the same process. In the test environment (Cloud Foundry), we will run the stubs in a separate process using a standalone stub runner application.
image::{cf-migration-root-docs}/greeting_ui_test_flow.png[title=""greeting-ui Test Flow""]
As in the build phase, without stubs we expect the response to be the hystrix fallback response that is hard-coded in `greeting-ui`. With stubs, however, we can expect the response that was declared in the contract.
We will rely on Spring Cloud Pipelines to:
* Deploy a stub runner application
* Provide the stub runner application the necessary information to download the stubs
* Open a port on the stub runner application for each stub
We will rely on the stub runner application to:
* Download the stubs from our maven repo (Bintray)
* Expose each stub on a separate port
* Register each stub in the Service Discovery server
The following steps describe how to configure this.
*Provide standalone stub runner app jar*
In the Prep step for this tutorial, you cloned the https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot[cloudfoundry-stub-runner-boot] repo to your local machine. The next step is to build this app and upload it to Bintray to make the jar available to Spring Cloud Pipelines.
As mentioned in Stage 1 of this tutorial, Bintray requires that a package exist before any app artifacts can be uploaded. Log into the Bintray UI and create a package for `cloudfoundry-stub-runner-boot`. If you forked this repo, you can use the `Import from GitHub` option. Otherwise, create the package manually and choose any license (e.g. Apache 2.0).
Now you are ready to build and upload this app to Bintray. The following script shows cloning, building and uploading. Edit as appropriate to match your Bintray URL, the Bintray ID in your `~/.m2/settings/xml` file, and the `cloudfoundry-stub-runner-boot` repo URL if you chose to fork it.
```bash
# Edit to match your Bintray URL and M2 repo ID setting (check your ~/.m2/settings.xml file)
MAVEN_REPO_URL=https://api.bintray.com/maven/ciberkleid/maven-repo/cloudfoundry-stub-runner-boot
MAVEN_REPO_ID=bintray
# Clone cloudfoundry-stub-runner-boot
git clone https://github.com/spring-cloud-samples/cloudfoundry-stub-runner-boot.git
cd cloudfoundry-stub-runner-boot
# Build and upload
./mvnw clean deploy -Ddistribution.management.release.url=""${MAVEN_REPO_URL}"" -Ddistribution.management.release.id=""${MAVEN_REPO_ID}""
```
You should now see the `cloudfoundry-stub-runner-boot` artifacts uploaded on Bintray.
*Provide standalone stub runner app manifest*
Next, we add a manifest file for the stub runner app for deployment to Cloud Foundry.
We will place this file in the `greeting-ui` repo. The file name and location can be your choice. For this example, we will use `sc-pipelines/manifest-stubrunner.yml`:
image::{cf-migration-root-docs}/greeting_ui_stubrunner_manifest.png[title=""greeting-ui Stub Runner Manifest""]
We populate this `manifest-stubrunner.yml` with the content shown below so that the stub runner binds to `service-registry`. The stub runner will register the `fortune-service` stub there so that `greeting-ui` can discover it in the same way it will discover the actual `fortune-service` app endpoint in stage and prod. From the `greeting-ui` perspective, there is no difference in how it interacts with Eureka and the stub runner app in test and the way it will interact with Eureka and the `fortune-service` app in stage and prod.
```yml
---
applications:
- name: stubrunner
timeout: 120
services:
- service-registry
env:
JAVA_OPTS: -Djava.security.egd=file:///dev/urandom
TRUST_CERTS: api.run.pivotal.io
```
*Provide stub runner jar and manifest info to the pipeline*
Now that we have a jar file and manifest file for our stub runner app, we need to provide this information to our `greeting-ui` pipeline so that the pipeline downloads the jar from Bintray and deploys it to Cloud Foundry. We do this through the `greeting-ui` `sc-pipelines.yml` file. We add an entry to the list of services in the `test` section, as follows:
```yml
- name: stubrunner
type: stubrunner
coordinates: io.pivotal:cloudfoundry-stub-runner-boot:0.0.1.M1
pathToManifest: sc-pipelines/manifest-stubrunner.yml
```
Notice that `name` matches the name of the app in `manifest-stubrunner.yml`, `coordinates` corresponds to the jar coordinates on the maven repo, and `pathToManifest` matches our chosen fie name for the stub runner app manifest.
Note also the `type` is set to `stubrunner`, which Spring Cloud Pipelines will recognize as a stanalone stub runner app and treat accordingly.
*Provide stub configuration for stub runner app*
The final steps in the configuration of the standalone stub runner app are:
* Enable the stub runner app to download the `fortune-service` stub from Bintray
* Open a second port on the container to receive requests for this stub
To accomplish this, we put stub and port configuration information into the properties section of the `greeting-ui` `pom.xml` file, using a property called `stubrunner.ids`. This property can accept a list of stubrunner ids, but for this tutorial, we only have one:
```xml
...
io.pivotal:fortune-service:1.0.0.M1-20180102_203542-VERSION:stubs:10000
```
Spring Cloud Pipelines will use this information in two ways:
. It will provide this information to the stub runner app via the app's environment variables
- Spring Cloud Pipelines will aslo provide the `$REPO_WITH_BINARIES` as an env var for the stub runner app
- The stub runner app will use this information to download the stub from Bintray and expose it on the specified port
. It will open the additional port specified on the stub runner app and map a new route to it
- The format for each route will be `----.`
- In our example, this would be `stubrunner-cyi-test-greeting-ui-10000.cfapps.io`
Since we bound our stub runner app to `service-registry` (Eureka), the stub runner app will register the stub URL under the application name `FORTUNE-SERVICE` on Eureka:
image::{cf-migration-root-docs}/greeting_ui_stub_runner_eureka_registration.png[title=""greeting-ui Stub Runner Eureka Registration""]
This completes the process of configuring the standalone stub runner application.
NOTE: The port configuration may be automated by Spring Cloud Pipelines in the future, such that it will not be necessary to include the port in the `stubrunner.ids`, but for the moment, we are required to specify the port each stub should use.
*Edit smoke tests to align with the contract*
Finally, we edit our smoke tests for `greeting-ui` to ensure the response does *not* contain the hystrix fallback, since we are noe expecting a response from the stub.
```java
package smoke;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmokeTests.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE)
@EnableAutoConfiguration
public class SmokeTests {
@Value(""${application.url}"") String applicationUrl;
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_return_a_fortune() {
ResponseEntity response = this.restTemplate
.getForEntity(""http://"" + this.applicationUrl + ""/"", String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
// Filter out the known Hystrix fallback response
BDDAssertions.then(response.getBody()).doesNotContain(""This fortune is no good. Try another."");
}
}
```
In this case, in contrast to the integration test we created earlier for `greeting-ui`, we do not include `@AutoConfigureStubRunner` since we are using a standalone stub runner application.
===== 3.9 Push changes to GitHub
Push contract-based changes for `greeting-ui`. You should be pushing the following new or modified files:
* pom.xml
* sc-pipelines.yml
* sc-pipelines/manifest-stubrunner.yml
* src/test/java/io/pivotal/fortune/FortuneServiceTests.java
* src/test/java/smoke/SmokeTests.java
At this point, we can run through the full pipeline for `greeting-ui` and leverage the contract-based stub in both the build and test environments.
===== Stage 3 Recap
What have we accomplished?
By implementing a contract-driven approach with auto-generation of tests and stubs, we have introduced a clean, structured, and reliable way to define, communicate, document, manage and test APIs
* Inter-team communication will be simpler
- Consumer and producer teams can now communicate requirements through codified contracts
- The inventory of contracts serves as a record and reference for the agreed upon APIs
* Developer productivity will increase
- Producers can quickly and easily generate contract-based stubs
- Consumers no longer have to manually stub out APIs and write tests with arbitrary hard-coded responses - instead they can use the auto-generated stubs and test for contract-based responses
- Both producers and consumers can validate they are compliant with the contract
- Producers can verify backward compatibility of API changes
- Troubleshooting will be easier
- Failure and feedback will be faster
=== Conclusion
This concludes the tutorial on migrating apps for Spring Cloud Pipelines for Cloud Foundry.
Moving forward, the refactoring work needed here can be incorporated into your and/or your team's standard practices. In short:
*Good:*
* Use maven or gradle wrappers
* Include a Cloud Foundry manifest file in your app repo
* Include a pipeline descriptor (`sc-manifest.yml`) in your app repo
* Create an empty `version` branch in your app repo
* Include artifact repository configuration in the pom.xml file
* Align your Cloud Foundry spaces with Spring Cloud Pipelines model (isolated test space, shared stage and prod)
*Better*
* Include default, apicompatibility, smoke, and e2e profiles in the pom.xml file
* Organize tests accordingly in your app repo
*Best*
* Use a database migration tool like flyway
* Use contract-based API programming
Implementing all the *""good""* practices above already positions you to instantly create pipelines for your apps usign Spring Cloud Pipelines. This is a huge win in terms of consistency and productivity, and standardization across development teams. Of course, this is an open source project, so it can be modified to meet your needs.
Implementing the *""better""* practices will ensure the proper tests get run at the proper time. At that point you can add as much test coverage as you need to have high confidence in your pipelines.
Implementing the *""best""* practices will give you additional confidence in your pipeline and encourage better programming practices for database version and API management across development teams. It will also give you higher confidence in your pipelines and enable you to avoid the cumbersome business of rolling back a database.
Happy coding!
",16208,True,2809.148711728697,median
"= Microsoft Service Bus Connector 2.2 Reference - Mule 4
:page-aliases: connectors::ms-service-bus/ms-service-bus-connector-reference.adoc
Support Category: https://www.mulesoft.com/legal/versioning-back-support-policy#anypoint-connectors[Select]
Release Notes: xref:release-notes::connector/ms-service-bus-connector-release-notes-mule-4.adoc[Microsoft Service Bus Connector Release Notes]
NOTE: This connector supports connecting only to the Microsoft Windows Service Bus on-premises solution. To connect to Microsoft Azure Service Bus, use https://www.mulesoft.com/exchange/com.mulesoft.connectors/mule-azure-service-bus-connector[Anypoint Connector for Azure Service Bus].
== Configurations
---
[[config]]
=== Default Configuration
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
|Name | String | Name for this configuration. Connectors reference the configuration with this name. | | x
| Connection a| * <>
* <>
* <>
| Connection types to provide to this configuration | | x
| Encoding a| String | Default encoding of the Message body to use if the message doesn't communicate it | |
| Content Type a| String | Default contentType of the Message body to use if the message doesn't communicate it | `/` |
| Expiration Policy a| <> | Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the instance expires at the exact moment that it becomes eligible. Mule purges the instances as appropriate. | |
| Ack Mode a| Enumeration, one of:
** IMMEDIATE
** AUTO
** MANUAL
** DUPS_OK | The `org.mule.jms.commons.api.config.ConsumerAckMode` to use when consuming a message. Override this setting at the message source level. This attribute must be `IMMEDIATE` if `transactionType` is `LOCAL` or `MULTI` | `AUTO` |
| Consumer Type a| One of:
* <>
* <> | The ConsumerType to use by default when consuming a Message. Override this setting at the message source level. | |
| Persistent Delivery a| Boolean | Sets the default value for the Message#getJMSDeliveryMode. If true, the DeliveryMode#PERSISTENT mode is used, which instructs the JMS provider to take extra care to insure the message is not lost in transit due to a JMS provider failure. | false |
| Priority a| Number | Defines the default Message#getJMSPriority to use when sending messages | 4 |
| Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded | 0 |
| Time To Live Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | A TimeUnit which qualifies the #timeToLive attribute. Defaults to MILLISECONDS | MILLISECONDS |
| Disable Message Id a| Boolean | Defines the default value to use when producing messages, for disabling the Message#getJMSMessageID generation in the broker. Depending on the provider it may or may not have effect | false |
| Disable Message Timestamp a| Boolean | Defines the default value to use, when producing messages, for disable Message#getJMSTimestamp generation in the broker. Depending on the provider it may or may not have effect. | false |
| Delivery Delay a| Number | Determines the Message delivery delay time which is calculated by adding the deliveryDelay value specified on the send method to the time the message was sent. Only used in JMS_2_0 | |
| Delivery Delay Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | A TimeUnit which qualifies the #deliveryDelay attribute. Defaults to MILLISECONDS | MILLISECONDS |
| Jms Type a| String | A message JMSType identifier supplied by a client when a message is sent. | |
|===
==== Connection Types
[[config_shared-access-signature]]
===== Shared Access Signature (Deprecated)
====== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false |
| Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 |
| Caching Strategy a| One of:
* no-caching
* <> | Strategy to use for caching sessions and connections | |
| Service Namespace a| String | | | x
| Storage Account Name a| String | (Optional) The account name of the Blob Storage to use to store large messages. | |
| Storage Access Key a| String | (Optional) The account key of the Blob Storage to use to store large messages. | |
| Container Name a| String | (Optional) The container name in the Blob Storage to use to store large messages. If this parameter is not provided, a default container is created. | |
| Shared Access Signature a| String | | |
| SAS tokens provider a| SharedAccessSignatureProvider | Provider instance that provides SAS tokens when required. | |
| SAS tokens list a| Array of String | List of SAS tokens to use when required. | |
| Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 |
| Outcome a| Enumeration, one of:
** ACCEPTED
** REJECTED
** RELEASED
** MODIFIED_FAILED
** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE |
| Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` |
|===
[[config_username-password]]
===== Username Password (Deprecated)
====== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false |
| Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 |
| Caching Strategy a| One of:
* no-caching
* <> | The strategy to use for caching sessions and connections | |
| Service Namespace a| String | | | x
| Storage Account Name a| String | (Optional) The account name of the Blob Storage to use to store large messages | |
| Storage Access Key a| String | (Optional) The account key of the Blob Storage to use to store large messages. | |
| Container Name a| String | (Optional) The container name in the Blob Storage to use to store large messages. If this parameter is not provided, a default container is created. | |
| Shared Access Key Name a| String | | | x
| Shared Access Key a| String | | | x
| Proxy a| <> | | |
| Security a| <> | | |
| Advanced a| <> | | |
| Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 |
| Outcome a| Enumeration, one of:
** ACCEPTED
** REJECTED
** RELEASED
** MODIFIED_FAILED
** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE |
| Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` |
|===
[[config_windows]]
===== Windows
====== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Skip connectivity test a| Boolean | (Optional) Skips the connectivity test at connector startup (use this if your access policy is restricted). | false |
| Max Connections a| Number | Maximum number of connections to keep in pool for the producer to reuse. If set to `-1`, a new connection is created every time. | -1 |
| Caching Strategy a| One of:
* no-caching
* <> | The strategy to use for caching sessions and connections | |
| Service Namespace a| String | | | x
| Username a| String | | | x
| Password a| String | | | x
| Fully Qualified Domain Name a| String | | | x
| Port a| String | | 9355 |
| Disable SSL certificate validation a| Boolean | | false |
| Idle timeout a| Number | The idle timeout in milliseconds after which the connection fails if the peer sends no AMQP frames. | 60000 |
| Proxy a| <> | | |
| Security a| <> | | |
| Advanced a| <> | | |
| Max redeliveries a| Number | Controls when an incoming message is rejected based on the number of times it was redelivered. The default value is -1 (disabled). A value of `0` means that no message redeliveries are accepted. A value of `5` means that a message is redelivered five times, and so forth. | -1 |
| Outcome a| Enumeration, one of:
** ACCEPTED
** REJECTED
** RELEASED
** MODIFIED_FAILED
** MODIFIED_FAILED_UNDELIVERABLE | Controls the outcome to apply to a message that is rejected due to exceeding the configured maxRedeliveries value. | MODIFIED_FAILED_UNDELIVERABLE |
| Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | `true` |
|===
== Operations
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
* <>
=== Associated Sources
* <>
[[ack]]
=== Ack
``
Allows the user to perform an ACK when the JmsAckMode#MANUAL mode is elected while consuming the Message. As per JMS Spec, performing an ACK over a single Message automatically works as an ACK for all the Messages produced in the same JmsSession.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Ack Id a| String | The AckId of the Message to ACK | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
== Types
[[Proxy]]
=== Proxy
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Field | Type | Description | Default Value | Required
| Host a| String | Host of the proxy | |
| Port a| String | Port of the proxy | |
| Username a| String | Username of the proxy | |
| Password a| String | Password for the proxy | |
|===
[[Advanced]]
=== Advanced
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Name | Type | Description | Default Value | Required
| Read Timeout a| Number | Amount of time that the client waits for a response before it times out. Zero (`0`) specifies that the client waits indefinitely. | 60000 |
| Read Timeout Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit for Read Timeout. | MILLISECONDS | {nbsp}
| Connection Timeout a| Number | The amount of time that the client attempts to establish a connection before it times out. Zero (`0`) specifies that the client continues to attempt to open a connection indefinitely. | 60000 | {nbsp}
| Connection Timeout Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit for Connection Timeout | MILLISECONDS | {nbsp} | | |
|===
[[Tls]]
=== TLS
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Field | Type | Description | Default Value | Required
| Enabled Protocols a| String | A comma-separated list of protocols enabled for this context | |
| Enabled Cipher Suites a| String | A comma-separated list of cipher suites enabled for this context | |
| Trust Store a| <> | | |
| Key Store a| <> | | |
| Revocation Check a| * <>
* <>
* <> | | |
|===
[[TrustStore]]
=== Trust Store
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Field | Type | Description | Default Value | Required
| Path a| String | Location, which is resolved relative to the current classpath and file system if possible, of the truststore | |
| Password a| String | Password used to protect the truststore | |
| Type a| String | Type of store used | |
| Algorithm a| String | Algorithm used by the truststore | |
| Insecure a| Boolean | If `true`, no certificate validations are performed, rendering connections vulnerable to attacks. Use at your own risk. | |
|===
[[KeyStore]]
=== Key Store
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Field | Type | Description | Default Value | Required
| Path a| String | Location, which is resolved relative to the current classpath and file system, if possible, of the keystore | |
| Type a| String | Type of store used | |
| Alias a| String | When the keystore contains many private keys, this attribute indicates the alias of the key to use. If not defined, the first key in the file is used by default. | |
| Key Password a| String | Password used to protect the private key | |
| Password a| String | Password used to protect the keystore | |
| Algorithm a| String | Algorithm used by the keystore | |
|===
[[standard-revocation-check]]
=== Standard Revocation Check
[%header,cols=""20s,25a,30a,15a,10a""]
|===
| Field | Type | Description | Default Value | Required
| Only End Entities a| Boolean | Only verify the last element of the certificate chain. | |
| Prefer Crls a| Boolean | Try CRL instead of OCSP first. | |
| No Fallback a| Boolean | Do not use the secondary checking method (the one not previously selected). | |
| Soft Fail a| Boolean | Avoid verification failure when the revocation server can't be reached or is busy. | |
|===
[[queueCreate]]
=== Queue Create
``
Creates a queue in the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Queue Path a| String | The name of the queue | | x
| Queue Description a| <> | An InternalQueueDescription object containing the desired values of the queue's properties to create | `#[payload]` |
| Target Variable a| String | Name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[queueDelete]]
=== Queue Delete
``
Deletes the specified queue in the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Queue Path a| String | Name of the queue | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | Retry strategy in case of connectivity errors | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[queueGet]]
=== Queue Get
``
This operation retrieves the specified queue from the Service Bus instance.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Queue Path a| String | Name of the queue | `#[payload]` |
| Target Variable a| String | Name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | Retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[queueSend]]
=== Queue Send
``
This operation sends a message to a queue.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Destination Queue a| String | The name of the queue. | | x
| Transactional Action a| Enumeration, one of:
** ALWAYS_JOIN
** JOIN_IF_POSSIBLE
** NOT_SUPPORTED | Type of transactional action. | NOT_SUPPORTED |
| Send Correlation Id a| Enumeration, one of:
** AUTO
** ALWAYS
** NEVER | Correlation strategy id for operation. | AUTO |
| Body a| Any | The body of the Message | `#[payload]` |
| JMS Type a| String | The JMSType identifier header of the Message | |
| Correlation ID a| String | The JMSCorrelationID header of the Message | |
| Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true |
| Content Type a| String | The content type of the message's body | |
| Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true |
| Encoding a| String | The encoding of the message's body | |
| Reply To a| <> | The destination where a reply to this Message should be sent | |
| User Properties a| Object | The custom user properties to set for this message | |
| JMSX Properties a| <> | The JMSX properties to set for this message | |
| Persistent Delivery a| Boolean | If true, the Message is sent using the PERSISTENT JMSDeliveryMode. | |
| Priority a| Number | The default JMSPriority value to use when sending the message. | |
| Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded. | |
| Time To Live Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the timeToLive configurations. | |
| Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID. | |
| Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp. | |
| Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | |
| Delivery Delay Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the deliveryDelay configurations. | |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[queueUpdate]]
=== Queue Update
``
This operation updates the specified queue in the Service Bus instance.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Queue Path a| String | The name of the queue | | x
| Queue Description a| <> | An InternalQueueDescription oject containing the desired values of the queue's properties that will be updated | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[queues]]
=== Queues
``
This operation retrieves all existing queues from the Service Bus instance.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |Array of <>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[recoverSession]]
=== Recover Session
``
Allows the user to recover a session when the JmsAckMode#MANUAL mode is elected while consuming the message. Per the JMS Spec, performing a session recover automatically redelivers all the consumed messages that were not acknowledged before the recover.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Ack Id a| String | The AckId of the Message Session to recover | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | Retry strategy in case of connectivity errors | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[ruleCreate]]
=== Rule Create
``
This operation creates a rule for the specified topic and subscription.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Rule Path a| String | Name of the rule to create | | x
| Rule Description a| <> | An InternalRuleDescription object containing the desired values of the new rule's properties | `#[payload]` |
| Topic Path a| String | Name of the topic that contains the subscription for which to create a rule | | x
| Subscription Path a| String | Name of the subscription that contains the new rule | |
| Target Variable a| String | Name of a variable that stores the operation's output | |
| Target Value a| String | Expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[ruleDelete]]
=== Rule Delete
``
This operation deletes a rule from the specified topic and subscription.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Topic Path a| String | Name of the topic that contains the subscription from which to delete the rule | | x
| Subscription Path a| String | Name of the subscription from which to delete the rule | | x
| Rule Path a| String | Name of the rule to delete | | x
| Reconnection Strategy a| * <>
* <> | Retry strategy in case of connectivity errors | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[ruleGet]]
=== Rule Get
``
This operation retrieves a rule from the specified topic and subscription.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | Name of the configuration to use | | x
| Topic Path a| String | Name of the topic that contains the subscription from which to retrieve the rule || x
| Subscription Path a| String | Name of the subscription from which to retrieve the rule | | x
| Rule Path a| String | Name of the rule to retrieve | | x
| Target Variable a| String | Name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[ruleUpdate]]
=== Rule Update
``
This operation updates a rule from the specified topic and subscription.
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Rule Description a| <> | An InternalRuleDescription object containing the desired values for the rule's updated properties | `#[payload]` |
| Topic Path a| String | The name of the topic that contains the subscription for which to update the rule | | x
| Subscription Path a| String | The name of the subscription for which to update the rule | | x
| Rule Path a| String | The name of the rule to update | | x
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[rules]]
=== Rules
``
Retrieves all rules from the specified topic and subscription
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Topic Path a| String | The name of the topic that contains the subscription from which to retrieve all rules | | x
| Subscription Path a| String | The name of the subscription from which to retrieve all rules | |
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |Array of <>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[subscriptionCreate]]
=== Subscription Create
``
Creates a subscription in the specified topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Topic Path a| String | The name of the topic to contain the new subscription | | x
| Subscription Path a| String | The name of the subscription to create | | x
| Subscription Description a| <> | An InternalSubscriptionDescription object containing the desired values of the new subscription's properties | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[subscriptionDelete]]
=== Subscription Delete
``
Deletes a subscription from the specified topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Topic Path a| String | The name of the topic from which to delete the subscription | | x
| Subscription Path a| String | The name of the subscription to delete | |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[subscriptionGet]]
=== Subscription Get
``
Retrieves a subscription from the specified topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use
| | x
| Topic Path a| String | The name of the topic from which to retrieve the subscription
| | x
| Subscription Path a| String | The name of the subscription to retrieve | |
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[subscriptionUpdate]]
=== Subscription Update
``
Updates a subscription from the specified topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Subscription Description a| <> | An InternalSubscriptionDescription object containing the desired values of the subscription's updated properties| `#[payload]` |
| Topic Path a| String | The name of the topic from which to update the subscription | | x
| Subscription Path a| String | The name of the subscription to update | |
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[subscriptions]]
=== Subscriptions
``
Retrieves all subscriptions from the specified topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use | | x
| Topic Path a| String | The name of the topic from which to retrieve all subscriptions | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |Array of <>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topicCreate]]
=== Topic Create
``
Creates a topic in the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Topic Path a| String | The name of the topic | | x
| Topic Description a| <> | An InternalTopicDescription object containing the desired values of the topic's properties that will be created. | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topicDelete]]
=== Topic Delete
``
Deletes the specified topic from the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Topic Path a| String | The name of the topic | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topicGet]]
=== Topic Get
``
Retrieves the specified topic from the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Topic Path a| String | The name of the topic | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topicSend]]
=== Topic Send
``
Sends a message to a Topic
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Destination Topic a| String | The name of the topic. | | x
| Transactional Action a| Enumeration, one of:
** ALWAYS_JOIN
** JOIN_IF_POSSIBLE
** NOT_SUPPORTED | Type of transactional action. | | x
| Send Correlation Id a| Enumeration, one of:
** AUTO
** ALWAYS
** NEVER | Correlation strategy id for operation. | | x
| Body a| Any | The body of the Message | `#[payload]` |
| JMS Type a| String | The JMSType identifier header of the Message | |
| Correlation ID a| String | The JMSCorrelationID header of the Message | |
| Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true |
| Content Type a| String | The content type of the message's body | |
| Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true |
| Encoding a| String | The encoding of the message's body | |
| Reply To a| <> | The destination where a reply to this Message should be sent | |
| User Properties a| Object | The custom user properties to set for this message | |
| JMSX Properties a| <> | The JMSX properties to set for this message | |
| Persistent Delivery a| Boolean | If true, the Message is sent using the PERSISTENT JMSDeliveryMode. | |
| Priority a| Number | The default JMSPriority value to use when sending the message. | |
| Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded. | |
| Time To Live Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the timeToLive configurations. | |
| Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID. | |
| Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp. | |
| Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | |
| Delivery Delay Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the deliveryDelay configurations. | |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topicUpdate]]
=== Topic Update
``
Updates the specified topic from the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Topic Path a| String | The name of the topic | | x
| Topic Description a| <> | An InternalTopicDescription object containing the desired values of the topic's properties that will be updated. | `#[payload]` |
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |<>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
[[topics]]
=== Topics
``
Retrieves all existing topics from the service bus instance
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Target Variable a| String | The name of a variable that stores the operation's output. | |
| Target Value a| String | An expression that evaluates the operation's output. The expression outcome is stored in the target variable. | `#[payload]` |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
|===
==== Output
[%autowidth.spread]
|===
|Type |Array of <>
|===
=== For Configurations
* <>
==== Throws
* SERVICEBUS:INVALID_TOKEN
* SERVICEBUS:RETRY_EXHAUSTED
* SERVICEBUS:CONNECTION_EXCEPTION
* SERVICEBUS:UNKNOWN
* SERVICEBUS:AMQP_ERROR
* SERVICEBUS:CONNECTIVITY
* SERVICEBUS:REST_ERROR
== Sources
[[listener]]
=== Listener
``
==== Parameters
[%header%autowidth.spread]
|===
| Name | Type | Description | Default Value | Required
| Configuration | String | The name of the configuration to use. | | x
| Ack Mode a| Enumeration, one of:
** IMMEDIATE
** AUTO
** MANUAL
** DUPS_OK | The Session ACK mode to use when consuming a message | |
| Number Of Consumers a| Number | The number of concurrent consumers to use to receive JMS Messages | 1 |
| Primary Node Only a| Boolean | Whether this source should be executed only on the primary node when running in a cluster | |
| Redelivery Policy a| <> | Defines a policy for processing the redelivery of the same message | |
| Source Type a| String | | | x
| Destination a| String | | | x
| Subscription a| String | | | x
| Content Type a| String | | |
| Encoding a| String | | |
| Reconnection Strategy a| * <>
* <> | A retry strategy in case of connectivity errors. | |
| Body a| Any | The body of the Message | `#[payload]` |
| JMS Type a| String | The JMSType identifier header of the Message | |
| Correlation ID a| String | The JMSCorrelationID header of the Message | |
| Send Content Type a| Boolean | Whether or not the body content type should be sent as a property | true |
| Content Type a| String | The content type of the message's body | |
| Send Encoding a| Boolean | Whether or not the body outboundEncoding should be sent as a Message property | true |
| Encoding a| String | The encoding of the message's body | |
| Reply To a| <> | The destination where a reply to this Message should be sent | |
| User Properties a| Object | The custom user properties to set for this message | |
| JMSX Properties a| <> | The JMSX properties to set for this message | |
| Persistent Delivery a| Boolean | Whether or not the delivery should be done with a persistent configuration | |
| Priority a| Number | The default JMSPriority value to use when sending the message | |
| Time To Live a| Number | Defines the default time the message is in the broker before it expires and is discarded | |
| Time To Live Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the timeToLive configurations | |
| Disable Message Id a| Boolean | If true, flags the message to avoid generating its MessageID | |
| Disable Message Timestamp a| Boolean | If true, flags the message to avoid generating its sent Timestamp | |
| Delivery Delay a| Number | Only used by JMS 2.0. Sets the delivery delay to apply to postpone the message delivery. | |
| Delivery Delay Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | Time unit to use in the deliveryDelay configurations | |
|===
==== Output
[%autowidth.spread]
|===
|Type |Message
| Attributes Type a| <>
|===
=== For Configurations
* <>
== Types
[[Reconnection]]
=== Reconnection
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Fails Deployment a| Boolean | When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | |
| Reconnection Strategy a| * <>
* <> | The reconnection strategy to use. | |
|===
[[reconnect]]
=== Reconnect
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Frequency a| Number | How often in milliseconds to reconnect. | |
| Count a| Number | How many reconnection attempts to make. | |
| blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true |
|===
[[reconnect-forever]]
=== Reconnect Forever
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Frequency a| Number | How often in milliseconds to reconnect. | |
| blocking |Boolean |If false, the reconnection strategy runs in a separate, non-blocking thread. |true |
|===
[[ExpirationPolicy]]
=== Expiration Policy
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Max Idle Time a| Number | A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it's considered eligible for expiration | |
| Time Unit a| Enumeration, one of:
** NANOSECONDS
** MICROSECONDS
** MILLISECONDS
** SECONDS
** MINUTES
** HOURS
** DAYS | A time unit that qualifies the maxIdleTime attribute | |
|===
[[ServiceBusJmsAttributes]]
=== Service Bus JMS Attributes
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Properties a| <> | | | x
| Headers a| <> | | | x
| Ack Id a| String | | |
|===
[[JmsMessageProperties]]
=== JMS Message Properties
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| All a| Object | | | x
| User Properties a| Object | | | x
| Jms Properties a| Object | | | x
| Jmsx Properties a| <> | | | x
|===
[[JmsxProperties]]
=== JMSX Properties
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Jmsx User ID a| String | | |
| Jmsx App ID a| String | | |
| Jmsx Delivery Count a| Number | | |
| Jmsx Group ID a| String | | |
| Jmsx Group Seq a| Number | | |
| Jmsx Producer TXID a| String | | |
| Jmsx Consumer TXID a| String | | |
| Jmsx Rcv Timestamp a| Number | | |
|===
[[JmsHeaders]]
=== JMS Headers
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Destination a| <> | | | x
| Delivery Mode a| Number | | | x
| Expiration a| Number | | | x
| Priority a| Number | | | x
| Message Id a| String | | |
| Timestamp a| Number | | | x
| Correlation Id a| String | | |
| Reply To a| <> | | |
| Type a| String | | | x
| Redelivered a| Boolean | | false |
| Delivery Time a| Number | | |
|===
[[RedeliveryPolicy]]
=== Redelivery Policy
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Max Redelivery Count a| Number | The maximum number of times a message can be redelivered and processed unsuccessfully before triggering process-failed-message | |
| Use Secure Hash a| Boolean | Whether to use a secure hash algorithm to identify a redelivered message. | |
| Message Digest Algorithm a| String | The secure hashing algorithm to use. | SHA-256 |
| Id Expression a| String | Defines one or more expressions used to determine when a message has been redelivered. This property can be set only when useSecureHash is false. | |
| Object Store a| Object Store | The object store where the redelivery counter for each message is going to be stored. | |
|===
[[ServiceBusJmsDestination]]
=== Service Bus JMS Destination
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Destination a| String | | | x
| Destination Type a| Enumeration, one of:
** QUEUE
** TOPIC | | QUEUE |
|===
[[ServiceBusQueue]]
=== Service Bus Queue
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Author a| String | | |
| Id a| String | | |
| Link a| String | | |
| Published a| Date | | |
| Queue Description a| <> | | |
| Title a| String | | |
| Updated a| Date | | |
|===
[[ServiceBusQueueDescription]]
=== Service Bus Queue Description
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Lock Duration a| String | Determines the amount of time in seconds in which a message should be locked for processing by a receiver. After this period, the message is unlocked and available for
consumption by the next receiver. Settable only at queue creation time. Valid values: Range: 0 - 5 minutes. 0 means that the message is not locked. Format: PTx3Mx4S, where
x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT5M (5 minutes), PT1M30S (1 minute, 30 seconds)). | PT1M |
| Max Size In Megabytes a| Number | Specifies the maximum queue size in megabytes. Any attempt to enqueue a message that causes the queue to exceed this value fails. Valid values are: 1024, 2048, 3072, 4096, 5120 | 1024 |
| Requires Duplicate Detection a| Boolean | Settable only at queue creation time. | false |
| Requires Session a| Boolean | Settable only at queue creation time. If set to true, the queue will be session-aware and only SessionReceiver will be supported. Session-aware queues are not supported
through REST. | false |
| Dead Lettering On Message Expiration a| Boolean | This field controls how the Service Bus handles a message with an expired TTL. If it is enabled and a message expires, Service Bus moves the message from the queue into the
queue's dead-letter sub-queue. If disabled, message is permanently deleted from the queue. Settable only at queue creation time. | false |
| Enable Batched Operations a| Boolean | Enables or disables service-side batching behavior when performing operations for the specific queue. When enabled, Service Bus collects or batches multiple operations to the
back end, to be more efficient with the connection. If you want lower operation latency, you can disable this feature. | true |
| Default Message Time To Live a| String | Depending on whether DeadLettering is enabled, a message is automatically moved to the DeadLetterQueue or deleted if it has been stored in the queue for longer than the
specified time. This value is overwritten by a TTL specified on the message if and only if the message TTL is smaller than the TTL set on the queue. This value is immutable
after the queue has been created. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours) | P10675199DT2H48M5.4775807S |
| Duplicate Detection History Time Window a| String | Specifies the time span during which Service Bus detects message duplication Valid values: Range: 1 second - 7 days. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2
number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | PT10M |
| Max Delivery Count a| Number | The maximum number of times Service Bus tries to deliver a message before being dead-lettered or discarded. | 10 |
|===
[[ServiceBusRule]]
=== Service Bus Rule
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Id a| String | | |
| Link a| String | | |
| Published a| Date | | |
| Rule Description a| <> | | |
| Title a| String | | |
| Updated a| Date | | |
|===
[[ServiceBusRuleDescription]]
=== Service Bus Rule Description
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Action a| <> | The action that the rule performs | |
| Filter a| <> | The filter for the associated subscription | |
|===
[[ServiceBusRuleAction]]
=== Service Bus Rule Action
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Sql Expression a| String | The SQL expression for the action to perform | |
| Type a| Enumeration, one of:
** SqlRuleAction
** EmptyRuleAction | | |
|===
[[ServiceBusRuleFilter]]
=== Service Bus Rule Filter
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Correlation Id a| String | The ID to match if this filter is a correlation filter | |
| Sql Expression a| String | The SQL expression for the action to perform | |
| Type a| Enumeration, one of:
** SqlFilter
** TrueFilter
** FalseFilter
** CorrelationFilter | | |
|===
[[ServiceBusSubscription]]
=== Service Bus Subscription
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Id a| String | | |
| Link a| String | | |
| Published a| Date | | |
| Subscription Description a| <> | | |
| Title a| String | | |
| Updated a| Date | | |
|===
[[ServiceBusSubscriptionDescription]]
=== Service Bus Subscription Description
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Lock Duration a| String | The default lock duration is applied to subscriptions that do not define a lock duration. You can only set this property at subscription creation time. Valid values: Range:
0 - 5 minutes. 0 means that the message is not locked. Format: PTx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples:
PT5M (5 minutes), PT1M30S (1 minute, 30 seconds)). | PT1M |
| Requires Session a| Boolean | You can only set this property at subscription creation time. If set to true, the subscription will be session-aware and only SessionReceiver will be supported.
Session-aware subscriptions are not supported through REST. | false |
| Dead Lettering On Message Expiration a| Boolean | This field controls how Service Bus handles a message with an expired TTL. If it is enabled and a message expires, Service Bus moves the message from the queue into the
subscription's dead-letter sub-queue. If disabled, message is permanently deleted from the subscription's main queue. Settable only at subscription creation time. | false |
| Dead Lettering On Filter Evaluation Exceptions a| Boolean | Determines how Service Bus handles a message that causes an exception during a subscription's filter evaluation. If the value is set to true, the message that caused the
exception is moved to the subscription's dead-letter queue. Otherwise, it is discarded. By default, this parameter is set to true, enabling you to investigate the cause of
the exception. It can occur from a malformed message or some incorrect assumptions being made in the filter about the form of the message. Settable only at subscription
creation time. | false |
| Enable Batched Operations a| Boolean | Enables or disables service-side batching behavior when performing operations for the specific queue. When enabled, Service Bus will collect/batch multiple operations to the
backend to be more connection efficient. If you want lower operation latency, then you can disable this feature. | false |
| Default Message Time To Live a| String | Determines how long a message lives in the subscription. Based on whether dead-lettering is enabled, a message whose Time To Live (TTL) has expired is either moved to the
subscription's associated DeadLetterQueue, or permanently deleted. If the topic specifies a smaller TTL than the subscription, the topic TTL is applied. Format:
Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours) | P10675199DT2H48M5.4775807S |
| Max Delivery Count a| Number | The maximum number of times Service Bus tries to deliver a message before that message is dead lettered or discarded. | 10 |
|===
[[ServiceBusTopic]]
=== Service Bus Topic
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Author a| String | | |
| Id a| String | | |
| Link a| String | | |
| Published a| Date | | |
| Title a| String | | |
| Topic Description a| <> | | |
| Updated a| Date | | |
|===
[[ServiceBusTopicDescription]]
=== Service Bus Topic Description
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Max Size In Megabytes a| Number | Specifies the maximum queue size in megabytes. Any attempt to enqueue a message that will cause the queue to exceed this value fails. Valid values are: 1024, 2048, 3072,
4096, 5120 | 1024 |
| Requires Duplicate Detection a| Boolean | If enabled, the topic detects duplicate messages within the time span specified by the DuplicateDetectionHistoryTimeWindow property. Settable only at topic creation time. | false |
| Enable Batched Operations a| Boolean | Enables or disables service side batching behavior when performing operations for the specific queue. When enabled, Service Bus collects/batches multiple operations to the
back end to be more connection efficient. If you want lower operation latency, you can disable this feature. | true |
| Default Message Time To Live a| String | Determines how long a message lives in the associated subscriptions. Subscriptions inherit the TTL from the topic unless they are created explicitly with a smaller TTL.
Based on whether dead-lettering is enabled, a message whose TTL has expired will either be moved to the subscription's associated DeadLetterQueue or will be permanently
deleted. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2 number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | P10675199DT2H48M5.4775807S |
| Duplicate Detection History Time Window a| String | Specifies the time span during which Service Bus detects message duplication Valid values: Range: 1 second - 7 days. Format: Px1DTx2Hx3Mx4S, where x1 number of days, x2
number of hours, x3 number of minutes, x4 number of seconds (Examples: PT10M (10 minutes), P1DT2H (1 day, 2 hours)). | PT10M |
|===
[[default-caching]]
=== Default Caching
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Session Cache Size a| Number | Number of sessions to cache. | |
| Cache Producers a| Boolean | true if the ConnectionFactory should cache the MessageProducers | true |
| Cache Consumers a| Boolean | true if the ConnectionFactory should cache the MessageConsumers | true |
|===
[[topic-consumer]]
=== Topic Consumer
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Topic Consumer a| <> | | | x
| Topic Subscription a| <> | | | x
|===
[[TopicSubscription]]
=== Topic Subscription
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Topic Path a| String | | | x
| Subscription Path a| String | | |
|===
[[ServiceBusQueueConsumer]]
=== Service Bus Queue Consumer
[%header%autowidth.spread]
|===
| Field | Type | Description | Default Value | Required
| Queue Consumer a| queue-consumer | | |
| Source Queue a| String | | |
| Number Of Consumers a| Number | The number of concurrent consumers to use to receive JMS Messages | 4 |
|===
== See Also
https://help.mulesoft.com[MuleSoft Help Center]
",16204,True,3804.1296479619614,median
"= bpftrace(8)
:doctype: manpage
:toc: true
////
Style guide:
- one sentence per line
////
== Name
bpftrace - a high-level tracing language
== Synopsis
*bpftrace* [_OPTIONS_] _FILENAME_ +
*bpftrace* [_OPTIONS_] -e 'program code'
== Description
bpftrace is a high-level tracing language and runtime for Linux based on BPF.
It supports static and dynamic tracing for both the kernel and user-space.
When _FILENAME_ is ""_-_"", read from stdin.
== Examples
List all probes with ""sleep"" in their name::
----
# bpftrace -l '*sleep*'
----
Trace processes calling sleep::
----
# bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }'
----
Trace processes calling sleep while spawning `sleep 5` as a child process::
----
# bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' -c 'sleep 5'
----
== Supported architectures
x86_64, arm64 and s390x
== Options
////
Custom prefix to easily link section
////
:idprefix: flags_
=== Output format
*-B* _MODE_::
Set the buffer mode for stdout. Valid values are::
*none* No buffering. Each I/O is written as soon as possible +
*line* Data is written on the first newline or when the buffer is full.
This is the default mode. +
*full* Data is written once the buffer is full.
*-f* _FORMAT_::
Set the output format. Valid values are::
*json* +
*text*
*-o* _FILENAME_::
Write bpftrace tracing output to _FILENAME_ instead of stdout.
This doesn't include child process (*-c* option) output.
Errors are still written to stderr.
*--no-warnings*::
Suppress all warning messages created by bpftrace.
=== Tracing
*-e* _PROGRAM_::
Execute _PROGRAM_ instead of reading the program from a file
*-I* _DIR_::
Add the directory _DIR_ to the search path for C headers.
This option can be used multiple times.
*--include* _FILENAME_::
Add _FILENAME_ as an include for the pre-processor.
This is equal to adding '#include _FILENAME_' to the start bpftrace program.
This option can be used multiple times.
*-l* [_SEARCH_]::
List all probes that match the _SEARCH_ pattern.
If the pattern is omitted all probes will be listed.
This pattern supports wildcards in the same way that probes do.
E.g. '-l kprobe:*file*' to list all 'kprobes' with 'file' in the
name. For more details see the <> section.
*--unsafe*::
Some calls, like 'system', are marked as unsafe as they can have dangerous side effects ('system(""rm -rf"")') and are disabled by default.
This flag allows their use.
*-k*::
Errors from bpf-helpers(7) are silently ignored by default which can lead to strange results.
This flag enables the detection of errors (except for errors from 'probe_read_*').
When errors occurs bpftrace will log an error containing the source location and the error code:
----
stdin:48-57: WARNING: Failed to probe_read_user_str: Bad address (-14)
u:lib.so:""fn(char const*)"" { printf(""arg0:%s\\n"", str(arg0));}
~~~~~~~~~
----
*-kk*::
Same as '-k' but also includes the errors from 'probe_read_*' helpers.
=== Process management
*-p* _PID_::
Attach to the process with _PID_. If the process terminates, bpftrace will also terminate.
When using USDT probes they will be attached to only this process.
*-c* _COMMAND_::
Run _COMMAND_ as a child process.
When the child terminates bpftrace stops as well, as if 'exit()' has been called.
If bpftrace terminates before the child process does the child process will be terminated with a SIGTERM.
If used, 'USDT' probes these will only be attached to the child process.
To avoid a race condition when using 'USDTs' the child is stopped after 'execve' using 'ptrace(2)' and continued when all 'USDT' probes are attached. +
The child PID is available to programs as the 'cpid' builtin. +
The child process runs with the same privileges as bpftrace itself (usually root).
*--usdt-file-activation*::
activate usdt semaphores based on file path
=== Miscellaneous
*--info*::
Print detailed information about features supported by the kernel and the bpftrace build.
*-h, --help*::
Print the help summary
*-V, --version*::
Print bpftrace version information
*-v*::
verbose messages
*-d*::
debug mode
*-dd*::
verbose debug mode
////
!
!
!
This prefix reset must be at the end of the section, else cross references break
!
!
////
== Environment Variables
Some behavior can only be controlled through environment variables.
This section lists all those variables.
////
Custom prefix to easily link section
////
:idprefix: envvar_
=== BPFTRACE_STRLEN
Default: 64
Number of bytes allocated on the BPF stack for the string returned by `str()`.
Make this larger if you wish to read bigger strings with str().
Beware that the BPF stack is small (512 bytes).
Support for even larger strings is [being discussed](https://github.com/iovisor/bpftrace/issues/305).
=== BPFTRACE_NO_CPP_DEMANGLE
Default: 0
C++ symbol demangling in user space stack traces is enabled by default.
This feature can be turned off by setting the value of this environment variable to `1`.
=== BPFTRACE_MAP_KEYS_MAX
Default: 4096
This is the maximum number of keys that can be stored in a map.
Increasing the value will consume more memory and increase startup times.
There are some cases where you will want to: for example, sampling stack traces, recording timestamps for each page, etc.
=== BPFTRACE_MAX_PROBES
Default: 512
This is the maximum number of probes that bpftrace can attach to.
Increasing the value will consume more memory, increase startup times and can incur high performance overhead or even freeze or crash the system.
=== BPFTRACE_CACHE_USER_SYMBOLS
Default: 0 if ASLR is enabled on system and `-c` option is not given; otherwise 1
By default, bpftrace caches the results of symbols resolutions only when ASLR (Address Space Layout Randomization) is disabled.
This is because the symbol addresses change with each execution with ASLR.
However, disabling caching may incur some performance penalty.
Set this env variable to 1 to force bpftrace to cache.
=== BPFTRACE_VMLINUX
Default: None
This specifies the vmlinux path used for kernel symbol resolution when attaching kprobe to offset.
If this value is not given, bpftrace searches vmlinux from pre defined locations.
See src/attached_probe.cpp:find_vmlinux() for details.
=== BPFTRACE_BTF
Default: None
The path to a BTF file.
By default, bpftrace searches several locations to find a BTF file.
See src/btf.cpp for the details.
=== BPFTRACE_PERF_RB_PAGES
Default: 64
Number of pages to allocate per CPU for perf ring buffer.
The value must be a power of 2.
If you're getting a lot of dropped events bpftrace may not be processing events in the ring buffer fast enough.
It may be useful to bump the value higher so more events can be queued up.
The tradeoff is that bpftrace will use more memory.
=== BPFTRACE_MAX_BPF_PROGS
Default: 512
This is the maximum number of BPF programs (functions) that bpftrace can generate.
The main purpose of this limit is to prevent bpftrace from hanging since generating a lot of probes
takes a lot of resources (and it should not happen often).
////
!
!
!
This prefix reset must be at the end of the section, else cross references break
!
!
////
:idprefix: _
////
Custom prefix to easily link to a section
////
:idprefix: language_
== bpftrace Language
=== Overview
The `bpftrace` (`bt`) language is inspired by the D language used by `dtrace` and uses the same program structure.
Each script consists of an preamble and one or more action blocks.
----
preamble
actionblock1
actionblock2
----
Preprocessor and type definitions take place in the preamble:
----
#include
#define RED ""\\033[31m""
struct S {
int x;
}
----
Each action block consists of three parts:
----
probe[,probe]
/predicate/ {
action
}
----
Probes::
A probe specifies the event and event type to attach too.
Predicate::
The predicate is optional condition that must be met for the action to be executed.
Action::
Actions are the programs that run when an event fires (and the predicate is met).
An action is a semicolon (`;`) separated list of statements and always enclosed by brackets `{}`
A basic script that traces the `open(2)` and `openat(2)` system calls can be written as follows:
----
BEGIN
{
printf(""Tracing open syscalls... Hit Ctrl-C to end.\\n"");
}
tracepoint:syscalls:sys_enter_open,
tracepoint:syscalls:sys_enter_openat
{
printf(""%-6d %-16s %s\\n"", pid, comm, str(args->filename));
}
----
This script has two action blocks and a total of 3 probes.
The first action block uses the special `BEGIN` probe, which fires once during `bpftrace` startup.
This probe is used to print a header, indicating that the tracing has started.
The second action block uses two probes, one for `open` and one for `openat`, and defines an action that prints the file being `open` ed as well as the `pid` and `comm` of the process that execute the syscall.
See the <> section for details on the available probe types.
=== Identifiers
Identifiers must match the following regular expression: `[_a-zA-Z][_a-zA-Z0-9]*`
=== Comments
Both single line and multi line comments are supported.
----
// A single line comment
i:s:1 { // can also be used to comment inline
/*
a multi line comment
*/
print(/* inline comment block */ 1);
}
----
=== Data Types
The following fundamental integer types are provided by the language.
[cols=""~,~""]
|===
|*Type*
|*Description*
|uint8
|Unsigned 8 bit integer
|int8
|Signed 8 bit integer
|uint16
|Unsigned 16 bit integer
|int16
|Signed 16 bit integer
|uint32
|Unsigned 32 bit integer
|int32
|Signed 32 bit integer
|uint64
|Unsigned 64 bit integer
|int64
|Signed 64 bit integer
|===
==== Floating-point
Floating-point numbers are not supported by BPF and therefore not by bpftrace.
=== Constants
Integers constants can be defined in the following formats:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
- scientific (base 10)
Octal constants have to be prefixed with a `0`, e.g. `0123`.
Hexadecimal constants start with either `0x` or `0X`, e.g. `0x10`.
Scientific are written in the `e` format which is a shorthand for `m*10^n`, e.g. `$i = 2e3;`.
Note that scientific literals are integer only due to the lack of floating point support, `1e-3` is not valid.
To improve the readability of big literals a underscore `_` can be used as field separator, e.g. 1_000_123_000.
Integer suffixes as found in the C language are parsed by bpftrace to ensure compatibility with C headers/definitions but they're not used as size specifiers.
`123UL`, `123U` and `123LL` all result in the same integer type with a value of `123`.
Character constants can be defined by enclosing the character in single quotes, e.g. `$c = 'c';`.
String constants can be defined by enclosing the character string in double quotes, e.g. `$str = ""Hello world"";`.
Characters and strings support the following escape sequences:
[cols=""~,~""]
|===
| \\n
|Newline
| \\t
|Tab
| \\0nn
|Octal value nn
| \\xnn
|Hexadecimal value nn
|===
=== Type conversion
Integer and pointer types can be converted using explicit type conversion with an expression like:
----
$y = (uint32) $z;
$py = (int16 *) $pz;
----
Integer casts to a higher rank are sign extended.
Conversion to a lower rank is done by zeroing leading bits.
=== Operators and Expressions
==== Arithmetic Operators
The following operators are available for integer arithmetic:
[cols=""~,~""]
|===
| +
|integer addition
| -
|integer subtraction
| *
|integer multiplication
| /
|integer division
| %
|integer modulo
|===
// TODO: Words about integer conversion when types mismatch
==== Logical Operators
[cols=""~,~""]
|===
| &&
| Logical AND
| \\|\\|
| Logical OR
| !
| Logical NOT
|===
==== Bitwise Operators
[cols=""~,~""]
|===
| &
| AND
| \\|
| OR
| ^
| XOR
| <<
| Left shift the left-hand operand by the number of bits specified by the right-hand expression value
| >>
| Right shift the left-hand operand by the number of bits specified by the right-hand expression value
|===
==== Relational Operators
The following relational operators are defined for integers and pointers.
[cols=""~,~""]
|===
| <
| left-hand expression is less than right-hand
| \\<=
| left-hand expression is less than or equal to right-hand
| >
| left-hand expression is bigger than right-hand
| >=
| left-hand expression is bigger or equal to than right-hand
| ==
| left-hand expression equal to right-hand
| !=
| left-hand expression not equal to right-hand
|===
The following relation operators are available for comparing strings.
[cols=""~,~""]
|===
| ==
| left-hand string equal to right-hand
| !=
| left-hand string not equal to right-hand
|===
==== Assignment Operators
The following assignment operators can be used on both `map` and `scratch` variables:
[cols=""~,~""]
|===
| =
| Assignment, assign the right-hand expression to the left-hand variable
| <\\<=
| Update the variable with its value left shifted by the number of bits specified by the right-hand expression value
| >>=
| Update the variable with its value right shifted by the number of bits specified by the right-hand expression value
| +=
| Increment the variable by the right-hand expression value
| -=
| Decrement the variable by the right-hand expression value
| *=
| Multiple the variable by the right-hand expression value
| /=
| Divide the variable by the right-hand expression value
| %=
| Modulo the variable by the right-hand expression value
| &=
| Bitwise AND the variable by the right-hand expression value
| \\|=
| Bitwise OR the variable by the right-hand expression value
| ^=
| Bitwise XOR the variable by the right-hand expression value
|===
All these operators are syntactic sugar for combining assignment with the specified operator.
`@ -= 5` is equal to `@ = @ - 5`.
==== Increment and Decrement Operators
The increment (`\\++`) and decrement (`--`) operators can be used on integer and pointer variables to increment their value by one.
They can only be used on variables and can either be applied as prefix or suffix.
The difference is that the expression `x++` returns the original value of `x`, before it got incremented while `++x` returns the value of `x` post increment.
E.g.
----
$x = 10;
$y = $x--; // y = 10; x = 9
$a = 10;
$b = --$a; // a = 9; b = 9
----
Note that maps will be implicitly declared and initialized to 0 if not already declared or defined.
Scratch variables must be initialized before using these operators.
=== Variables and Maps
bpftrace knows two types of variables, `scratch` and `map`.
'scratch' variables are kept on the BPF stack and only exists during the execution of the action block and cannot be accessed outside of the program.
Scratch variable names always start with a `$`, e.g. `$myvar`.
'map' variables use BPF 'maps'.
These exist for the lifetime of `bpftrace` itself and can be accessed from all action blocks and user-space.
Map names always start with a `@`, e.g. `@mymap`.
All valid identifiers can be used as `name`.
The data type of a variable is automatically determined during first assignment and cannot be changed afterwards.
==== Associative Arrays
Associative arrays are a collection of elements indexed by a key, similar to the hash tables found in languages like C++ (`std::map`) and Python (`dict`).
They're a variant of 'map' variables.
----
@name[key] = expression
@name[key1,key2] = expression
----
Just like with any variable the type is determined on first use and cannot be modified afterwards.
This applies to both the key(s) and the value type.
The following snippet creates a map with key signature `[int64, string[16]]` and a value type of `int64`:
----
@[pid, comm]++
----
=== Variable scoping
// TODO
=== Pointers
Pointers in bpftrace are similar to those found in `C`.
// TODO, not true yet
=== Tuples
bpftrace has support for immutable N-tuples (`n > 1`).
A tuple is a sequence type (like an array) where, unlike an array, every element can have a different type.
Tuples are a comma separated list of expressions, enclosed in brackets, `(1,2)`
Individual fields can be accessed with the `.` operator.
Tuples are zero indexed like arrays are.
----
i:s:1 {
$a = (1,2);
$b = (3,4, $a);
print($a);
print($b);
print($b.0);
}
----
Prints:
----
(1, 2)
(3, 4, (1, 2))
3
----
==== Arrays
bpftrace supports accessing one-dimensional arrays like those found in `C`.
Constructing arrays from scratch, like `int a[] = {1,2,3}` in `C`, is not supported.
They can only be read into a variable from a pointer.
The `[]` operator is used to access elements.
----
struct MyStruct {
int y[4];
}
kprobe:dummy {
$s = (struct MyStruct *) arg0;
print($s->y[0]);
}
----
=== Structs
`C` like structs are supported by bpftrace.
Fields are accessed with the `.` operator.
Fields of a pointer to a struct can be accessed with the `\\->` operator.
Custom struct can be defined in the preamble
Constructing structs from scratch, like `struct X var = {.f1 = 1}` in `C`, is not supported.
They can only be read into a variable from a pointer.
----
struct MyStruct {
int a;
}
kprobe:dummy {
$ptr = (struct MyStruct *) arg0;
$st = *$ptr;
print($st.a);
print($ptr->a);
}
----
=== Conditionals
Conditional expressions are supported in the form of if/else statements and the ternary operator.
The ternary operator consists of three operands: a condition followed by a `?`, the expression to execute when the condition is true followed by a `:` and the expression to execute if the condition is false.
----
condition ? ifTrue : ifFalse
----
Both the `ifTrue` and `ifFalse` expressions must be of the same type, mixing types is not allowed.
The ternary operator can be used as part of an assignment.
----
$a == 1 ? print(""true"") : print(""false"");
$b = $a > 0 ? $a : -1;
----
If/else statements, like the one in `C`, are supported.
----
if (condition) {
ifblock
} else if (condition) {
if2block
} else {
elseblock
}
----
=== Loops
Since kernel 5.3 BPF supports loops as long as the verifier can prove they're bounded and fit within the instruction limit.
In bpftrace loops are available through the `while` statement.
----
while (condition) {
block;
}
----
Within a while-loop the following control flow statements can be used:
[cols=""~,~""]
|===
| continue
| skip processing of the rest of the block and jump back to the evaluation of the conditional
| break
| Terminate the loop
|===
----
i:s:1 {
$i = 0;
while ($i <= 100) {
printf(""%d "", $i);
if ($i > 5) {
break;
}
$i++
}
printf(""\\n"");
}
----
Loop unrolling is also supported with the `unroll` statement.
----
unroll(n) {
block;
}
----
The compiler will evaluate the block `n` times and generate the BPF code for the block `n` times.
As this happens at compile time `n` must be a constant greater than 0 (`n > 0`).
The following two probes compile into the same code:
----
i:s:1 {
unroll(3) {
print(""Unrolled"")
}
}
i:s:1 {
print(""Unrolled"")
print(""Unrolled"")
print(""Unrolled"")
}
----
////
!
!
!
This prefix reset must be at the end of the section, else cross references break
!
!
////
:idprefix: _
== Sync and Async
While BPF in the kernel can do a lot there are still things that can only be done from user space, like the outputting (printing) of data.
The way bpftrace handles this is by sending events from the BPF program which user-space will pick up some time in the future (usually in milliseconds).
Operations that happen in the kernel are 'synchronous' ('sync') and those that are handled in user space are 'asynchronous' ('async')
The async behaviour can lead to some unexpected behavior as updates can happen before user space had time to process the event.
One example is updating a map value in a tight loop:
----
BEGIN {
@=0;
unroll(10) {
print(@);
@++;
}
exit()
}
----
Maps are printed by reference not by value and as the value gets updated right after the print user-space will likely only see the final value once it processes the event:
----
@: 10
@: 10
@: 10
@: 10
@: 10
@: 10
@: 10
@: 10
@: 10
@: 10
----
== Address-spaces
Kernel and user pointers live in different address spaces which, depending on the CPU architecture, might overlap.
Trying to read a pointer that is in the wrong address space results in a runtime error.
This error is hidden by default but can be enabled with the `-kk` flag:
----
stdin:1:9-12: WARNING: Failed to probe_read_user: Bad address (-14)
BEGIN { @=*uptr(kaddr(""do_poweroff"")) }
~~~
----
bpftrace tries to automatically set the correct address space for a pointer based on the probe type, but might fail in cases where it is unclear.
The address space can be changed with the `kptr()` and `uptr()` functions.
== Builtins
Builtins are special variables built into the language.
Unlike the scratch and map variable they don't need a `$` or `@` as prefix (except for the positional parameters).
[%header,cols=""~,~,~,~,~""]
|===
| Variable
| Type
| Kernel
| BPF Helper
| Description
| `$1`, `$2`, `...$n`
| int64
| n/a
| n/a
| The nth positional parameter passed to the bpftrace program.
If less than n parameters are passed this evaluates to `0`.
For string arguments use the `str()` call to retrieve the value.
| `$#`
| int64
| n/a
| n/a
| Total amount of positional parameters passed.
| `arg0`, `arg1`, `...argn`
| int64
| n/a
| n/a
| nth argument passed to the function being traced. These are extracted from the CPU registers. The amount of args passed in registers depends on the CPU architecture. (kprobes, uprobes, usdt).
| cgroup
| uint64
| 4.18
| get_current_cgroup_id
| ID of the cgroup the current task is in. Only works with cgroupv2.
| comm
| string[16]
| 4.2
| get_current_com
| `comm` of the current task. Equal to the value in `/proc//comm`
| cpid
| uint32
| n/a
| n/a
| PID of the child process
| cpu
| uint32
| 4.1
| raw_smp_processor_id
| ID of the processor executing the BPF program
| curtask
| uint64
| 4.8
| get_current_task
| Pointer to `struct task_struct` of the current task
| elapsed
| uint64
| (see nsec)
| ktime_get_ns / ktime_get_boot_ns
| Nanoseconds elapsed since bpftrace initialization, based on `nsecs`
| func
| string
| n/a
| n/a
| Name of the current function being traced (kprobes,uprobes)
| gid
| uint64
| 4.2
| get_current_uid_gid
| GID of current task
| kstack
| kstack
|
| get_stackid
| Kernel stack trace
| nsecs
| uint64
| 4.1 / 5.7
| ktime_get_ns / ktime_get_boot_ns
| nanoseconds since kernel boot. On kernels that support `ktime_get_boot_ns` this includes the time spent suspended, on older kernels it does not.
| pid
| uint64
| 4.2
| get_current_pid_tgid
| Process ID (or thread group ID) of the current task.
| probe
| string
| n/na
| n/a
| Name of the current probe
| rand
| uint32
| 4.1
| get_prandom_u32
| Random number
| retval
| int64
| n/a
| n/a
| Value returned by the function being traced (kretprobe, uretprobe, kretfunc)
| `sarg0`, `sarg1`, `...sargn`
| int64
| n/a
| n/a
| nth stack value of the function being traced. (kprobes, uprobes).
| tid
| uint64
| 4.2
| get_current_pid_tgid
| Thread ID of the current task.
| uid
| uint64
| 4.2
| get_current_uid_gid
| UID of current task
| ustack
| ustack
| 4.6
| get_stackid
| Userspace stack trace
|===
////
Custom prefix to easily link to a function
////
:idprefix: functions_
== Map Functions
Map functions are built-in functions who's return value can only be assigned to maps.
The data type associated with these functions are only for internal use and are not compatible with the (integer) operators.
Functions that are marked *async* are asynchronous which can lead to unexpected behavior, see the <> section for more information.
=== avg
.variants
* `avg(int64 n)`
Calculate the running average of `n` between consecutive calls.
----
i:s:1 {
@x++;
@y = avg(@x);
print(@x);
print(@y);
}
----
Internally this keeps two values in the map: value count and running total.
The average is computed in user-space when printing by dividing the total by the count.
=== clear
.variants
* `clear(map m)`
*async*
Clear all keys/values from map `m`.
----
i:ms:100 {
@[rand % 10] = count();
}
i:s:10 {
print(@);
clear(@);
}
----
=== count
.variants
* `count()`
Count how often this function is called.
Using `@=count()` is conceptually similar to `@++`.
The difference is that the `count()` function uses a map type optimized for this (PER_CPU), increasing performance.
Due to this the map cannot be accessed as a regular integer.
----
i:ms:100 {
@ = count();
}
i:s:10 {
print(@);
clear(@);
}
----
=== delete
.variants
* `delete(mapkey k)`
Delete a single key from a map.
For a single value map this deletes the only element.
For an associative-array the key to delete has to be specified.
```
k:dummy {
@scalar = 1;
@associative[1,2] = 1;
delete(@scalar);
delete(@associative[1,2]);
delete(@associative); // error
}
```
=== hist
.variants
* `hist(int64 n)`
Create a log2 histogram of `n`.
----
kretprobe:vfs_read {
@bytes = hist(retval);
}
----
Results in:
----
@:
[1M, 2M) 3 | |
[2M, 4M) 2 | |
[4M, 8M) 2 | |
[8M, 16M) 6 | |
[16M, 32M) 16 | |
[32M, 64M) 27 | |
[64M, 128M) 48 |@ |
[128M, 256M) 98 |@@@ |
[256M, 512M) 191 |@@@@@@ |
[512M, 1G) 394 |@@@@@@@@@@@@@ |
[1G, 2G) 820 |@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
----
=== lhist
.variants
* `lhist(int64 n, int64 min, int64 max, int64 step)`
Create a linear histogram of `n`.
`lhist` creates `M` (`(max - min) / step`) buckets in the range `[min,max)` where each bucket is `step` in size.
Values in the range `(-inf, min)` and `(max, inf)` get their get their own bucket too, bringing the total amount of buckets created to `M+2`.
----
i:ms:1 {
@ = lhist(rand %10, 0, 10, 1);
}
i:s:5 {
exit();
}
----
Prints:
----
@:
[0, 1) 306 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[1, 2) 284 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[2, 3) 294 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[3, 4) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[4, 5) 311 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[5, 6) 362 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
[6, 7) 336 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[7, 8) 326 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[8, 9) 328 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
[9, 10) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ |
----
=== max
.variants
* `max(int64 n)`
Update the map with `n` if `n` is bigger than the current value held.
=== min
.variants
* `min(int64 n)`
Update the map with `n` if `n` is smaller than the current value held.
=== stats
.variants
* `stats(int64 n)`
`stats` combines the `count`, `avg` and `sum` calls into one.
----
kprobe:vfs_read {
@bytes[comm] = stats(arg2);
}
----
----
@bytes[bash]: count 7, average 1, total 7
@bytes[sleep]: count 5, average 832, total 4160
@bytes[ls]: count 7, average 886, total 6208
@
----
=== sum
.variants
* `sum(int64 n)`
Calculate the sum of all `n` passed.
=== zero
.variants
* `zero(map m)`
*async*
Set all values for all keys to zero.
== Functions
Functions that are marked *async* are asynchronous which can lead to unexpected behaviour, see the <> section for more information.
*compile time* functions are evaluated at compile time, a static value will be compiled into the program.
*unsafe* functions can have dangerous side effects and should be used with care, the `--unsafe` flag is required for use.
=== bswap
.variants
* `uint8 bswap(uint8 n)`
* `uint16 bswap(uint16 n)`
* `uint32 bswap(uint32 n)`
* `uint64 bswap(uint64 n)`
`bswap` reverses the order of the bytes in integer `n`. In case of 8 bit integers, `n` is returned without being modified.
The return type is an unsigned integer of the same width as `n`.
=== buf
.variants
* `buf_t buf(void * data, [int64 length])`
`buf` reads `length` amount of bytes from address `data`.
The maximum value of `length` is limited to the `BPFTRACE_STRLEN` variable.
For arrays the `length` is optional, it is automatically inferred from the signature.
`buf` is address space aware and will call the correct helper based on the address space associated with `data`.
The `buf_t` object returned by `buf` can safely be printed as a hex encoded string with the `%r` format specifier.
Bytes with values >=32 and \\<=126 are printed using their ASCII character, other bytes are printed in hex form (e.g. `\\x00`).
----
i:s:1 {
printf(""%r\\n"", buf(kaddr(""avenrun""), 8));
}
----
----
\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00
\\xc2\\x02\\x00\\x00\\x00\\x00\\x00\\x00
----
=== cat
.variants
* `void cat(string namefmt, [...args])`
*async*
Dump the contents of the named file to stdout.
`cat` supports the same format string and arguments that `printf` does.
If the file cannot be opened or read an error is printed to stderr.
----
t:syscalls:sys_enter_execve {
cat(""/proc/%d/maps"", pid);
}
----
----
55f683ebd000-55f683ec1000 r--p 00000000 08:01 1843399 /usr/bin/ls
55f683ec1000-55f683ed6000 r-xp 00004000 08:01 1843399 /usr/bin/ls
55f683ed6000-55f683edf000 r--p 00019000 08:01 1843399 /usr/bin/ls
55f683edf000-55f683ee2000 rw-p 00021000 08:01 1843399 /usr/bin/ls
55f683ee2000-55f683ee3000 rw-p 00000000 00:00 0
----
=== cgroup_path
.variants
* `cgroup_path cgroup_path(int cgroupid, string filter)`
Convert cgroup id to cgroup path.
This is done asynchronously in userspace when the cgroup_path value is printed,
therefore it can resolve to a different value if the cgroup id gets reassigned.
This also means that the returned value can only be used for printing.
A string literal may be passed as an optional second argument to filter cgroup
hierarchies in which the cgroup id is looked up by a wildcard expression (cgroup2
is always represented by ""unified"", regardless of where it is mounted).
The currently mounted hierarchy at /sys/fs/cgroup is used to do the lookup. If
the cgroup with the given id isn't present here (e.g. when running in a Docker
container), the cgroup path won't be found (unlike when looking up the cgroup
path of a process via /proc/.../cgroup).
----
BEGIN {
$cgroup_path = cgroup_path(3436);
print($cgroup_path);
print($cgroup_path); /* This may print a different path */
printf(""%s %s"", $cgroup_path, $cgroup_path); /* This may print two different paths */
}
----
=== cgroupid
.variants
* `uint64 cgroupid(const string path)`
*compile time*
`cgroupid` retrieves the cgroupv2 ID of the cgroup available at `path`.
----
BEGIN {
print(cgroupid(""/sys/fs/cgroup/system.slice""));
}
----
=== exit
.variants
* `void exit()`
*async*
Terminate bpftrace, as if a `SIGTERM` was received.
The `END` probe will still trigger (if specified) and maps will be printed.
=== join
.variants
* `void join(char *arr[], [char * sep = ' '])`
*async*
`join` joins all the string array `arr` with `sep` as separator into one string.
This string will be printed to stdout directly, it cannot be used as string value.
The concatenation of the array members is done in BPF and the printing happens in userspace.
----
tracepoint:syscalls:sys_enter_execve {
join(args->argv);
}
----
=== kaddr
.variants
* `uint64 kaddr(const string name)`
*compile time*
Get the address of the kernel symbol `name`.
The following script:
=== kptr
.variants
* `T * kptr(T * ptr)`
Marks `ptr` as a kernel address space pointer.
See the address-spaces section for more information on address-spaces.
The pointer type is left unchanged.
=== ksym
.variants
* `ksym_t ksym(uint64 addr)`
*async*
Retrieve the name of the function that contains address `addr`.
The address to name mapping happens in user-space.
The `ksym_t` type can be printed with the `%s` format specifier.
----
kprobe:do_nanosleep
{
printf(""%s\\n"", ksym(reg(""ip"")));
}
----
Prints:
----
do_nanosleep
----
=== macaddr
.variants
* `macaddr_t macaddr(char [6] mac)`
Create a buffer that holds a macaddress as read from `mac`
This buffer can be printed in the canonical string format using the `%s` format specifier.
----
kprobe:arp_create {
printf(""SRC %s, DST %s\\n"", macaddr(sarg0), macaddr(sarg1));
}
----
Prints:
----
SRC 18:C0:4D:08:2E:BB, DST 74:83:C2:7F:8C:FF
----
=== ntop
.variants
* `inet_t ntop([int64 af, ] int addr)`
* `inet_t ntop([int64 af, ] char addr[4])`
* `inet_t ntop([int64 af, ] char addr[16])`
`ntop` returns the string representation of an IPv4 or IPv6 address.
`ntop` will infer the address type (IPv4 or IPv6) based on the `addr` type and size.
If an integer or `char[4]` is given, ntop assumes IPv4, if a `char[16]` is given, ntop assumes IPv6.
You can also pass the address type (e.g. AF_INET) explicitly as the first parameter.
=== override
.variants
* `override(uint64 rc)`
*unsafe*
*Kernel* 4.16
*Helper* `bpf_override`
.Supported probes
* kprobe
When using `override` the probed function will not be executed and instead `rc` will be returned.
----
k:__x64_sys_getuid
/comm == ""id""/ {
override(2<<21);
}
----
----
uid=4194304 gid=0(root) euid=0(root) groups=0(root)
----
This feature only works on kernels compiled with `CONFIG_BPF_KPROBE_OVERRIDE` and only works on functions tagged `ALLOW_ERROR_INJECTION`.
bpftrace does not test whether error injection is allowed for the probed function, instead if will fail to load the program into the kernel:
----
ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument
Error attaching probe: 'kprobe:vfs_read'
----
=== reg
.variants
* `reg(const string name)`
.Supported probes
* kprobe
* uprobe
Get the contents of the register identified by `name`.
Valid names depend on the CPU architecture.
=== signal
.variants
* `signal(const string sig)`
* `signal(uint32 signum)`
*unsafe*
*Kernel* 5.3
*Helper* `bpf_send_signal`
Probe types: k(ret)probe, u(ret)probe, USDT, profile
Send a signal to the process being traced.
The signal can either be identified by name, e.g. `SIGSTOP` or by ID, e.g. `19` as found in `kill -l`.
----
kprobe:__x64_sys_execve
/comm == ""bash""/ {
signal(5);
}
----
----
$ ls
Trace/breakpoint trap (core dumped)
----
=== sizeof
.variants
* `sizeof(TYPE)`
* `sizeof(EXPRESSION)`
*compile time*
Returns size of the argument in bytes.
Similar to C/C++ `sizeof` operator.
Note that the expression does not get evaluated.
=== str
.variants
* `str(char * data [, uint32 length)`
*Helper* `probe_read_str, probe_read_{kernel,user}_str`
`str` reads a NULL terminated (`\\0`) string from `data`.
The maximum string length is limited by the `BPFTRACE_STR_LEN` env variable, unless `length` is specified and shorter than the maximum.
In case the string is longer than the specified length only `length - 1` bytes are copied and a NULL byte is appended at the end.
When available (starting from kernel 5.5, see the `--info` flag) bpftrace will automatically use the `kernel` or `user` variant of `probe_read_{kernel,user}_str` based on the address space of `data`, see <> for more information.
=== strftime
.variants
* `strtime_t strftime(const string fmt, int64 timestamp_ns)`
*async*
Format the nanoseconds since boot timestamp `timestamp_ns` according to the format specified by `fmt`.
The time conversion and formatting happens in user space, therefore the `timestr_t` value returned can only be used for printing using the `%s` format specifier.
bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers.
----
i:s:1 {
printf(""%s\\n"", strftime(""%H:%M:%S"", nsecs));
}
----
bpftrace also supports the following format string extensions:
[%header,cols=""~,~""]
|===
| Specifier
| Description
| `%f`
| Microsecond as a decimal number, zero-padded on the left
|===
=== strncmp
.variants
* `int64 strncmp(char * s1, char * s2, int64 n)`
`strncmp` compares up to `n` characters string `s1` and string `s2`.
If they're equal `0` is returned, else a non-zero value is returned.
bpftrace doesn't read past the length of the shortest string.
The use of the `==` and `!=` operators is recommended over calling `strncmp` directly.
=== system
.variants
* `void system(string namefmt [, ...args])`
*unsafe*
*async*
`system` lets bpftrace run the specified command (`fork` and `exec`) until it completes and print its stdout.
The `command` is run with the same privileges as bpftrace and it blocks execution of the processing threads which can lead to missed events and delays processing of async events.
----
i:s:1 {
time(""%H:%M:%S: "");
printf(""%d\\n"", @++);
}
i:s:10 {
system(""/bin/sleep 10"");
}
i:s:30 {
exit();
}
----
Note how the async `time` and `printf` first print every second until the `i:s:10` probe hits, then they print every 10 seconds due to bpftrace blocking on `sleep`.
----
Attaching 3 probes...
08:50:37: 0
08:50:38: 1
08:50:39: 2
08:50:40: 3
08:50:41: 4
08:50:42: 5
08:50:43: 6
08:50:44: 7
08:50:45: 8
08:50:46: 9
08:50:56: 10
08:50:56: 11
08:50:56: 12
08:50:56: 13
08:50:56: 14
08:50:56: 15
08:50:56: 16
08:50:56: 17
08:50:56: 18
08:50:56: 19
----
`system` supports the same format string and arguments that `printf` does.
----
t:syscalls:sys_enter_execve {
system(""/bin/grep %s /proc/%d/status"", ""vmswap"", pid);
}
----
=== time
.variants
* `void time(const string fmt)`
*async*
Format the current wall time according to the format specifier `fmt` and print it to stdout.
Unlike `strftime()` `time()` doesn't send a timestamp from the probe, instead it is the time at which user-space processes the event.
bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers.
=== uaddr
.variants
* `T * uaddr(const string sym)`
.Supported probes
* uprobes
* uretprobes
* USDT
**Does not work with ASLR, see issue link:https://github.com/iovisor/bpftrace/issues/75[#75]**
The `uaddr` function returns the address of the specified symbol.
This lookup happens during program compilation and cannot be used dynamically.
The default return type is `uint64*`.
If the ELF object size matches a known integer size (1, 2, 4 or 8 bytes) the return type is modified to match the width (`uint8*`, `uint16*`, `uint32*` or `uint64*` resp.).
As ELF does not contain type info the type is always assumed to be unsigned.
----
uprobe:/bin/bash:readline {
printf(""PS1: %s\\n"", str(*uaddr(""ps1_prompt"")));
}
----
=== uptr
.variants
* `T * uptr(T * ptr)`
Marks `ptr` as a user address space pointer.
See the address-spaces section for more information on address-spaces.
The pointer type is left unchanged.
=== usym
.variants
* `usym_t usym(uint64 * addr)`
*async*
.Supported probes
* uprobes
* uretprobes
Equal to <> but resolves user space symbols
----
uprobe:/bin/bash:readline
{
printf(""%s\\n"", usym(reg(""ip"")));
}
----
Prints:
----
readline
----
=== path
.variants
* `char * path(struct path * path)`
*Kernel* 5.10
*Helper* bpf_d_path
Return full path referenced by struct path pointer in argument.
This function can only be used by functions that are allowed to, these functions are contained in the `btf_allowlist_d_path` set in the kernel.
=== unwatch
.variants
* `void unwatch(void * addr)`
*async*
Removes a watchpoint
== Output formatting
=== print
.variants
* `void print(T val)`
*async*
.variants
* `void print(T val)`
* `void print(@map)`
* `void print(@map, uint64 top)`
* `void print(@map, uint64 top, uint64 div)`
`print` prints a the value, which can be a map or a scalar value, with the default formatting for the type.
----
i:ms:10 { @=hist(rand); }
i:s:1 {
print(@);
print(123);
print(""abc"");
exit();
}
----
Prints:
----
@:
[16M, 32M) 3 |@@@ |
[32M, 64M) 2 |@@ |
[64M, 128M) 1 |@ |
[128M, 256M) 4 |@@@@ |
[256M, 512M) 3 |@@@ |
[512M, 1G) 14 |@@@@@@@@@@@@@@ |
[1G, 2G) 22 |@@@@@@@@@@@@@@@@@@@@@@ |
[2G, 4G) 51 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
123
abc
----
Note that maps are printed by reference while scalar values are copied.
This means that updating and printing maps in a fast loop will likely result in bogus map values as the map will be updated before userspace gets the time to dump and print it.
The printing of maps supports the optional `top` and `div` arguments.
`top` limits the printing to the top N entries with the highest integer values
----
BEGIN {
$i = 11;
while($i) {
@[$i] = --$i;
}
print(@, 2);
clear(@);
exit()
}
----
----
@[9]: 9
@[10]: 10
----
The `div` argument scales the values prior to printing them.
Scaling values before storing them can result in rounding errors.
Consider the following program:
----
k:f {
@[func] += arg0/10;
}
----
With the following sequence as numbers for arg0: `134, 377, 111, 99`.
The total is `721` which rounds to `72` when scaled by 10 but the program would print `70` due to the rounding of individual values.
Changing the print call to `print(@, 5, 2)` will take the top 5 values and scale them by 2:
----
@[6]: 3
@[7]: 3
@[8]: 4
@[9]: 4
@[10]: 5
----
=== printf
.variants
* `void printf(const string fmt, args...)`
*async*
`printf()` formats and prints data.
It behaves similar to `printf()` found in `C` and many other languages.
The format string has to be a constant, it cannot be modified at runtime.
The formatting of the string happens in user space.
Values are copied and passed by value.
bpftrace supports all the typical format specifiers like `%llx` and `%hhu`.
The non-standard ones can be found in the table below:
[%header,cols=""~,~,~""]
|===
| Specifier
| Type
| Description
| r
| buffer
| Hex-formatted string to print arbitrary binary content returned by the buf (<>) function.
|===
Supported escape sequences
Colors are supported too, using standard terminal escape sequences:
----
print(""\\033[31mRed\\t\\033[33mYellow\\033[0m\\n"")
----
////
!
!
!
This prefix reset must be at the end of the section, else cross references break
!
!
////
:idprefix: _
== Probes
bpftrace supports various probe types which allow the user to attach BPF programs to different types of events.
Each probe starts with a provider (e.g. `kprobe`) followed by a colon (`:`) separated list of options.
The amount of options and their meaning depend on the provider and are detailed below.
The valid values for options can depend on the system or binary being traced, e.g. for uprobes it depends on the binary.
Also see <>
It is possible to associate multiple probes with a single action as long as the action is valid for all specified probes.
Multiple probes can be specified as a comma (`,`) separated list:
----
kprobe:tcp_reset,kprobe:tcp_v4_rcv {
printf(""Entered: %s\\n"", probe);
}
----
Wildcards are supported too:
----
kprobe:tcp_* {
printf(""Entered: %s\\n"", probe);
}
----
Both can be combined:
----
kprobe:tcp_reset,kprobe:*socket* {
printf(""Entered: %s\\n"", probe);
}
----
Most providers also support a short name which can be used instead of the full name, e.g. `kprobe:f` and `k:f` are identical.
[#probes-begin-end]
=== BEGIN and END
These are special built-in events provided by the bpftrace runtime.
`BEGIN` is triggered before all other probes are attached.
`END` is triggered after all other probes are detached.
Note that specifying an `END` probe doesn't override the printing of 'non-empty' maps at exit.
To prevent the printing all used maps need be cleared, which can be done in the `END` probe:
----
END {
clear(@map1);
clear(@map2);
}
----
[#probes-hardware]
=== hardware
.variants
* `hardware:event_name:`
* `hardware:event_name:count`
.shortname
* `h`
The `hardware` probe attaches to pre-defined hardware events provided by the kernel.
They are implemented using performance monitoring counters (PMCs): hardware resources on the
processor. There are about ten of these, and they are documented in the `perf_event_open(2)` man page.
The event names are:
- `cpu-cycles` or `cycles`
- `instructions`
- `cache-references`
- `cache-misses`
- `branch-instructions` or `branches`
- `branch-misses`
- `bus-cycles`
- `frontend-stalls`
- `backend-stalls`
- `ref-cycles`
The `count` option specifies how many events must happen before the probe fires.
If `count` is left unspecified a default value is used.
----
hardware:cache-misses:1e6 { @[pid] = count(); }
----
[#probes-interval]
=== interval
.variants
* `interval:us:count`
* `interval:ms:count`
* `interval:s:count`
* `interval:hz:rate`
.shortnames
* `i`
The interval probe fires at a fixed interval as specified by its time spec.
Interval fire on one CPU at the time, unlike <> probes.
[#probes-iterator]
=== iterator
.variants
* `iter:task`
* `iter:task:pin`
* `iter:task_file`
* `iter:task_file:pin`
.shortnames
* `it`
These are eBPF iterator probes, that allow iteration over kernel objects.
Iterator probe can't be mixed with any other probe, not even other iterator.
Each iterator probe provides set of fields that could be accessed with
ctx pointer. User can display set of available fields for iterator via
-lv options as described below.
Examples:
```
# bpftrace -e 'iter:task { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }'
Attaching 1 probe...
systemd:1
kthreadd:2
rcu_gp:3
rcu_par_gp:4
kworker/0:0H:6
mm_percpu_wq:8
...
# bpftrace -e 'iter:task_file { printf(""%s:%d %d:%s\\n"", ctx->task->comm, ctx->task->pid, ctx->fd, path(ctx->file->f_path)); }'
Attaching 1 probe...
systemd:1 1:/dev/null
systemd:1 2:/dev/null
systemd:1 3:/dev/kmsg
...
su:1622 1:/dev/pts/1
su:1622 2:/dev/pts/1
su:1622 3:/var/lib/sss/mc/passwd
...
bpftrace:1892 1:pipe:[35124]
bpftrace:1892 2:/dev/pts/1
bpftrace:1892 3:anon_inode:bpf-map
bpftrace:1892 4:anon_inode:bpf-map
bpftrace:1892 5:anon_inode:bpf_link
bpftrace:1892 6:anon_inode:bpf-prog
bpftrace:1892 7:anon_inode:bpf_iter
```
It's possible to pin iterator with specifying optional probe ':pin' part, that defines the pin file.
It can be specified as absolute path or relative to /sys/fs/bpf.
.relative pin
----
# bpftrace -e 'iter:task:list { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }'
Program pinned to /sys/fs/bpf/list
----
----
# cat /sys/fs/bpf/list
systemd:1
kthreadd:2
rcu_gp:3
rcu_par_gp:4
kworker/0:0H:6
mm_percpu_wq:8
rcu_tasks_kthre:9
...
----
Examples with absolute pin file:
.absolute pin
----
# bpftrace -e '
iter:task_file:/sys/fs/bpf/files {
printf(""%s:%d %s\\n"", ctx->task->comm, ctx->task->pid, path(ctx->file->f_path));
}'
Program pinned to /sys/fs/bpf/files
----
----
# cat /sys/fs/bpf/files
systemd:1 anon_inode:inotify
systemd:1 anon_inode:[timerfd]
...
systemd-journal:849 /dev/kmsg
systemd-journal:849 anon_inode:[eventpoll]
...
sssd:1146 /var/log/sssd/sssd.log
sssd:1146 anon_inode:[eventpoll]
...
NetworkManager:1155 anon_inode:[eventfd]
NetworkManager:1155 /var/lib/sss/mc/passwd (deleted)
----
[#probes-kfunc]
=== kfunc and kretfunc
.variants
* `kfunc:fn`
* `kretfunc:fn`
.shortnames
* `f` (`kfunc`)
* `fr` (`kretfunc`)
.requires (`--info`)
* Kernel features:BTF
* Probe types:kfunc
``kfunc``s attach to kernel function similar to <>.
They make use of eBPF trampolines which allows kernel code to call into BPF programs with near zero overhead.
`kfunc` s make use of BTF type information to derive the type of function arguments at compile time.
This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel.
The function arguments are available in the `args` struct which can be inspected by doing verbose listing (see <>).
These arguments are also available in the return probe (`kretfunc`).
----
# bpftrace -lv 'kfunc:tcp_reset'
kfunc:tcp_reset
struct sock * sk
struct sk_buff * skb
----
----
kfunc:x86_pmu_stop {
printf(""pmu %s stop\\n"", str(args->event->pmu->name));
}
----
----
kretfunc:fget {
printf(""fd %d name %s\\n"", args->fd, str(retval->f_path.dentry->d_name.name));
}
----
----
fd 3 name ld.so.cache
fd 3 name libselinux.so.1
fd 3 name libselinux.so.1
...
----
[#probes-kprobe]
=== kprobe and kretprobe
.variants
* `kprobe:fn`
* `kprobe:fn+offset`
* `kretprobe:fn`
.shortnames
* `k`
* `kr`
`kprobe` s allow for dynamic instrumentation of kernel functions.
Each time the specified kernel function is executed the attached BPF programs are ran.
----
kprobe:tcp_reset {
@tcp_resets = count()
}
----
Function arguments are available through the `argX` and `sargX` builtins, for register args and stack args respectively.
Whether arguments passed on stack or in a register depends on the architecture and the number or arguments in used, e.g. on x86_64 the first non-floating point 6 arguments are passed in registers, all following arguments are passed on the stack.
Note that floating point arguments are typically passed in special registers which don't count as `argX` arguments which can cause confusion.
Consider a function with the following signature:
----
void func(int a, double d, int x)
----
Due to `d` being a floating point `x` is accessed through `arg1` where one might expect `arg2`.
bpftrace does not detect the function signature so it is not aware of the argument count or their type.
It is up to the user to perform <> when needed, e.g.
----
kprobe:tcp_connect
{
$sk = ((struct sock *) arg0);
...
}
----
`kprobe` s are not limited to function entry, they can be attached to any instruction in a function by specifying an offset from the start of the function.
`kretprobe` s trigger on the return from a kernel function.
Return probes do not have access to the function (input) arguments, only to the return value (through `retval`).
A common pattern to work around this is by storing the arguments in a map on function entry and retrieving in the return probe:
----
kprobe:d_lookup
{
$name = (struct qstr *)arg1;
@fname[tid] = $name->name;
}
kretprobe:d_lookup
/@fname[tid]/
{
printf(""%-8d %-6d %-16s M %s\\n"", elapsed / 1e6, pid, comm,
str(@fname[tid]));
}
----
[#probes-profile]
=== profile
.variants
* `profile:us:count`
* `profile:ms:count`
* `profile:s:count`
* `profile:hz:rate`
.shortnames
* `p`
Profile probes fire on each CPU on the specified interval.
[#probes-software]
=== software
.variants
* `software:event:`
* `software:event:count`
.shortnames
* `s`
The `software` probe attaches to pre-defined software events provided by the kernel.
Event details can be found in the `perf_event_open(2)` man page.
The event names are:
- `cpu-clock` or `cpu`
- `task-clock`
- `page-faults` or `faults`
- `context-switches` or `cs`
- `cpu-migrations`
- `minor-faults`
- `major-faults`
- `alignment-faults`
- `emulation-faults`
- `dummy`
- `bpf-output`
[#probes-tracepoint]
=== tracepoint
.variants
* `tracepoint:subsys:event`
.shortnames
* `t`
Tracepoints are hooks into events in the kernel.
Tracepoints are defined in the kernel source and compiled into the kernel binary which makes them a form of static tracing.
Which means that unlike `kprobe` s new tracepoints cannot be added without modifying the kernel.
The advantage of tracepoints is that they generally provide a more stable interface than `kprobe` s do, they do not depend on the existence of a kernel function.
Tracepoint arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details.
----
tracepoint:syscalls:sys_enter_openat {
printf(""%s %s\\n"", comm, str(args->filename));
}
----
----
irqbalance /proc/interrupts
irqbalance /proc/stat
snmpd /proc/diskstats
snmpd /proc/stat
snmpd /proc/vmstat
snmpd /proc/net/dev
[...]
----
.Additional information
* https://www.kernel.org/doc/html/latest/trace/tracepoints.html
[#probes-uprobe]
=== uprobe, uretprobe
.variants
* `uprobe:binary:func`
* `uprobe:binary:func+offset`
* `uretprobe:binary:func`
.shortnames
* `u`
* `ur`
`uprobe` s or user-space probes are the user-space equivalent of `kprobe` s.
The same limitations that apply <> also apply to `uprobe` s and `uretprobe` s.
When tracing libraries, it is sufficient to specify the library name instead of
a full path. The path will be then automatically resolved using `/etc/ld.so.cache`:
----
# bpftrace -e 'uprobe:libc:malloc { printf(""Allocated %d bytes\\n"", arg0); }'
Allocated 4 bytes
...
----
If the traced binary has DWARF included, function arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details.
It is important to note that for `uretprobe` s to work the kernel runs a special helper on user-space function entry which overrides the return address on the stack.
This can cause issues with languages that have their own runtime like Golang:
.example.go
----
func myprint(s string) {
fmt.Printf(""Input: %s\\n"", s)
}
func main() {
ss := []string{""a"", ""b"", ""c""}
for _, s := range ss {
go myprint(s)
}
time.Sleep(1*time.Second)
}
----
.bpftrace
----
# bpftrace -e 'uretprobe:./test:main.myprint { @=count(); }' -c ./test
runtime: unexpected return pc for main.myprint called from 0x7fffffffe000
stack: frame={sp:0xc00008cf60, fp:0xc00008cfd0} stack=[0xc00008c000,0xc00008d000)
fatal error: unknown caller pc
----
[#probes-usdt]
=== usdt
.variants
* `usdt:binary:name`
.shortnames
* `U`
[#probes-watchpoint]
=== watchpoint and asyncwatchpoint
.variants
* `watchpoint:absolute_address:length:mode`
* `watchpoint:function+argN:length:mode`
.shortnames
* `w`
* `aw`
These are memory watchpoints provided by the kernel. Whenever a memory address is written to (`w`), read
from (`r`), or executed (`x`), the kernel can generate an event.
In the first form, an absolute address is monitored. If a pid (`-p`) or a command (`-c`) is provided,
bpftrace takes the address as a userspace address and monitors the appropriate process. If not,
bpftrace takes the address as a kernel space address.
In the second form, the address present in `argN` when `function` is entered is
monitored. A pid or command must be provided for this form. If synchronous (`watchpoint`), a
`SIGSTOP` is sent to the tracee upon function entry. The tracee will be ``SIGCONT``ed after the
watchpoint is attached. This is to ensure events are not missed. If you want to avoid the
`SIGSTOP` + `SIGCONT` use `asyncwatchpoint`.
Note that on most architectures you may not monitor for execution while monitoring read or write.
Examples
Print `hit` when a read from or write to `0x10000000` happens:
```
# bpftrace -e 'watchpoint:0x10000000:8:rw { printf(""hit!\\n""); exit(); }' -c ./testprogs/watchpoint
```
Print the call stack every time the `jiffies` variable is updated:
```
# bpftrace -e ""watchpoint:0x$(awk '$3 == ""jiffies"" {print $1}' /proc/kallsyms):8:w {
@[kstack] = count();
}
i:s:1 { exit(); }""
......
@[
do_timer+12
tick_do_update_jiffies64.part.22+89
tick_sched_do_timer+103
tick_sched_timer+39
__hrtimer_run_queues+256
hrtimer_interrupt+256
smp_apic_timer_interrupt+106
apic_timer_interrupt+15
cpuidle_enter_state+188
cpuidle_enter+41
do_idle+536
cpu_startup_entry+25
start_secondary+355
secondary_startup_64+164
]: 319
```
""hit"" and exit when the memory pointed to by `arg1` of `increment` is written to.
```
# cat wpfunc.c
#include
#include
#include
__attribute__((noinline))
void increment(__attribute__((unused)) int _, int *i)
{
(*i)++;
}
int main()
{
int *i = malloc(sizeof(int));
while (1)
{
increment(0, i);
(*i)++;
usleep(1000);
}
}
# bpftrace -e 'watchpoint:increment+arg1:4:w { printf(""hit!\\n""); exit() }' -c ./wpfunc
```
== Listing Probes
Probe listing is the method to discover which probes are supported by the current system.
Listing supports the same syntax as normal attachment does:
----
# bpftrace -l 'kprobe:*'
# bpftrace -l 't:syscalls:*openat*
# bpftrace -l 'kprobe:tcp*,trace
# bpftrace -l 'k:*socket*,tracepoint:syscalls:*tcp*'
----
The verbose flag (`-v`) can be specified to inspect arguments (`args`) for providers that support it:
----
# bpftrace -l 'fr:tcp_reset,t:syscalls:sys_enter_openat' -v
kretfunc:tcp_reset
struct sock * sk
struct sk_buff * skb
tracepoint:syscalls:sys_enter_openat
int __syscall_nr
int dfd
const char * filename
int flags
umode_t mode
# bpftrace -l 'uprobe:/bin/bash:rl_set_prompt' -v # works only if /bin/bash has DWARF
uprobe:/bin/bash:rl_set_prompt
const char *prompt
----
",16217,True,2910.3516571349455,median
"