Version 1.3.0.RC1
© 2012-2017 Pivotal Software, Inc.
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
Getting Started
Spring Cloud Data Flow is a toolkit for building data integration and real-time data processing pipelines.
Pipelines consist of Spring Boot apps, built using the Spring Cloud Stream or Spring Cloud Task microservice frameworks. This makes Spring Cloud Data Flow suitable for a range of data processing use cases, from import/export to event streaming and predictive analytics.
This project provides support for using Spring Cloud Data Flow with Kubernetes as the runtime for these pipelines with apps packaged as Docker images.
1. Installation
In this section we will install the Spring Cloud Data Flow Server on a Kubernetes cluster. Spring Cloud Data Flow depends on a few services and their availability. For example, we need an RDBMS service for the app registry, stream/task repositories and task management. For streaming pipelines, we also need a transport option such as Apache Kafka or Rabbit MQ. In addition to this, we need a Redis service if the analytics features are in use.
This guide describes setting up an environment for testing Spring Cloud Data Flow on Google Kubernetes Engine and is not meant to be a definitive guide for setting up a production environment. Feel free to adjust the suggestions to fit your test set-up. Please remember that a production environment requires much more consideration for persistent storage of message queues, high availability, security etc. |
Currently, only apps registered with a Note that we do support Maven resources for the E.g. the below app registration is valid:
but any app registered with a Maven, HTTP or File resource for the executable jar (using a |
1.1. Kubernetes Compatibility
The Spring Cloud Data Flow implementation for Kubernetes uses Spring Cloud Deployer Kubernetes library for orchestration. Before you begin setting up Kubermetes cluster, refer to the compatibility-matrix to learn more about the deployer/server compatibility against Kubernetes release versions.
1.2. Create a Kubernetes cluster
The Kubernetes Picking the Right Solution guide lets you choose among many options so you can pick one that you are most comfortable using.
All our testing is done using the Google Kubernetes Engine that is part of the Google Cloud Platform. That is a also the target platform for this section. We have also successfully deployed using Minikube and we will note where you need to adjust for deploying on Minikube.
When starting Minikube you should allocate some extra resources since we will be deploying several services. We have used minikube start --cpus=4 --memory=4096 to start.
|
The rest of this getting started guide assumes that you have a working Kubernetes cluster and a kubectl
command line utility. See the docs for installation instructions: Installing and Setting up kubectl.
1.3. Deploying using kubectl
-
Get the Kubernetes configuration files.
There are sample deployment and service YAML files in the https://github.com/spring-cloud/spring-cloud-dataflow-server-kubernetes repository that you can use as a starting point. They have the required metadata set for service discovery by the different apps and services deployed. To check out the code enter the following commands:
$ git clone https://github.com/spring-cloud/spring-cloud-dataflow-server-kubernetes $ cd spring-cloud-dataflow-server-kubernetes $ git checkout v1.3.0.RC1
-
Deploy Rabbit MQ.
The Rabbit MQ service will be used for messaging between modules in the stream. You could also use Kafka, but, in order to simplify, we only show the Rabbit MQ configurations in this guide.
Run the following commands to start the Rabbit MQ service:
$ kubectl create -f src/kubernetes/rabbitmq/
You can use the command
kubectl get all -l app=rabbitmq
to verify that the deployment, pod and service resources are running. Use the commandkubectl delete all -l app=rabbitmq
to clean up afterwards. -
Deploy MySQL.
We are using MySQL for this guide, but you could use Postgres or H2 database instead. We include JDBC drivers for all three of these databases, you would just have to adjust the database URL and driver class name settings.
You can modify the password in the src/kubernetes/mysql/mysql-deployment.yaml
files if you prefer to be more secure. If you do modify the password you will also have to provide it base64 encoded in thesrc/kubernetes/mysql/mysql-secrets.yaml
file.Run the following commands to start the MySQL service:
$ kubectl create -f src/kubernetes/mysql/
You can use the command
kubectl get all -l app=mysql
to verify that the deployment, pod and service resources are running. Use the commandkubectl delete all,pvc,secrets -l app=mysql
to clean up afterwards. -
Deploy Redis.
The Redis service will be used for the analytics functionality. Run the following commands to start the Redis service:
$ kubectl create -f src/kubernetes/redis/
If you don’t need the analytics functionality you can turn this feature off by changing SPRING_CLOUD_DATAFLOW_FEATURES_ANALYTICS_ENABLED
to false in thesrc/kubernetes/server/server-deployment.yml
file. If you don’t install the Redis service then you should also remove the Redis configuration settings insrc/kubernetes/server/server-config-kafka.yml
mentioned below.You can use the command
kubectl get all -l app=redis
to verify that the deployment, pod and service resources are running. Use the commandkubectl delete all -l app=redis
to clean up afterwards. -
Deploy the Metrics Collector.
The Metrics Collector will provide message rates for all deployed stream apps. These message rates will be visible in the Dashboard UI. Run the following commands to start the Metrics Collector:
$ kubectl create -f src/kubernetes/metrics/metrics-deployment-rabbit.yaml $ kubectl create -f src/kubernetes/metrics/metrics-svc.yaml
You can use the command
kubectl get all -l app=metrics
to verify that the deployment, pod and service resources are running. Use the commandkubectl delete all -l app=metrics
to clean up afterwards. -
Deploy Skipper
Optionally, you can deploy Skipper to leverage the features of upgrading and rolling back Streams since Data Flow delegates to Skipper for those features. For more details, review Spring Cloud Skipper’s reference guide for a complete overview and its feature capabilities. Also, the Deploy Skipper section covers the internals in greater detail.
To use Skipper, you must uncomment the following properties to
src/kubernetes/skipper/skipper-deployment.yaml
. under theenv:
section- name: SPRING_CLOUD_SKIPPER_CLIENT_SERVER_URI value: 'http://${SKIPPER_SERVICE_HOST}/api' - name: SPRING_CLOUD_DATAFLOW_FEATURES_SKIPPER_ENABLED value: true
If you intend to use Skipper, run the following commands to start Skipper as the companion server for Spring Cloud Data Flow:
$ kubectl create -f src/kubernetes/skipper/skipper-deployment.yaml $ kubectl create -f src/kubernetes/skipper/skipper-svc.yaml
-
Deploy the Data Flow Server.
You should specify the version of the Spring Cloud Data Flow server that you want to deploy. The deployment is defined in the
src/kubernetes/server/server-deployment.yaml
file. To control what version of the Spring Cloud Data Flow server that gets deployed you should modify the tag used for the Docker image in the container spec:spec: containers: - name: scdf-server image: springcloud/spring-cloud-dataflow-server-kubernetes:1.3.0.RC1 (1) imagePullPolicy: Always
1 change the version as you like. This document is based on the 1.3.0.RC1
release.The Data Flow Server uses the Fabric8 Java client library to connect to the Kubernetes cluster. We are using environment variables to set the values needed when deploying the Data Flow server to Kubernetes. We are also using the Fabric8 Spring Cloud integration with Kubernetes library to access Kubernetes ConfigMap and Secrets settings. The ConfigMap settings are specified in the
src/kubernetes/server/server-config-rabbit.yaml
file and the secrets are in thesrc/kubernetes/mysql/mysql-secrets.yaml
file. If you modified the password for MySQL you should have changed it in thesrc/kubernetes/mysql/mysql-secrets.yaml
file. Any secrets have to be provided base64 encoded.We are now configuring the Data Flow server with file based security and the default user is 'user' with a password of 'password'. Feel free to change this in the src/kubernetes/server/server-config-rabbit.yaml
file.The default memory for the pods is set to 1024Mi. Update the value in the src/kubernetes/server/server-deployment.yaml
file if you expect most of your apps to require more memory.The latest releases of kubernetes have enabled RBAC on the api-server. If your target platform has RBAC enabled you must ask a cluster-admin
to create theroles
androle-bindings
for you before deploying the dataflow server. They associate the dataflow service account with the roles it needs to be run with.$ kubectl create -f src/kubernetes/server/server-roles.yaml $ kubectl create -f src/kubernetes/server/server-rolebinding.yaml
-
Deploy the Spring Cloud Data Flow Server for Kubernetes using the Docker image and the configuration settings.
$ kubectl create -f src/kubernetes/server/service-account.yaml $ kubectl create -f src/kubernetes/server/server-config-rabbit.yaml $ kubectl create -f src/kubernetes/server/server-svc.yaml $ kubectl create -f src/kubernetes/server/server-deployment.yaml
You can use the command
kubectl get all -l app=scdf-server
to verify that the deployment, pod and service resources are running. Use the commandkubectl delete all,cm -l app=scdf-server
to clean up afterwards.Use the
kubectl get svc scdf-server
command to locate the EXTERNAL_IP address assigned toscdf-server
, we will use that later to connect from the shell.$ kubectl get svc NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE scdf-server 10.103.246.82 130.211.203.246 80/TCP 4m skipper 10.103.246.83 130.211.203.247 80/TCP 5m
So the URL you need to use is in this case 130.211.203.246
If you are using Minikube then you don’t have an external load balancer and the EXTERNAL-IP will show as
<pending>
. You need to use the NodePort assigned for thescdf-server
service. Use this command to look up the URL to use:$ minikube service --url scdf-server http://192.168.99.100:31991
1.4. Deploy Skipper
This is an optional step. Deploy Skipper if you want the added features of upgrading and rolling back Streams since Data Flow delegates to Skipper for those features.
The Deployment resource for Skipper is shown below:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: skipper
labels:
app: skipper
spec:
replicas: 1
template:
metadata:
labels:
app: skipper
spec:
containers:
- name: skipper
image: springcloud/spring-cloud-skipper-server:1.0.0.RC4
imagePullPolicy: Always
ports:
- containerPort: 80
resources:
limits:
cpu: 1.0
memory: 1024Mi
requests:
cpu: 0.5
memory: 640Mi
env:
- name: SPRING_APPLICATION_JSON
value: "{\"spring.cloud.skipper.server.enable.local.platform\" : false, \"spring.cloud.skipper.server.platform.kubernetes.accounts.minikube.environmentVariables\" : \"SPRING_RABBITMQ_HOST=${RABBITMQ_SERVICE_HOST},SPRING_RABBITMQ_PORT=${RABBITMQ_SERVICE_PORT}\",\"spring.cloud.skipper.server.platform.kubernetes.accounts.minikube.memory\" : \"1024Mi\",\"spring.cloud.skipper.server.platform.kubernetes.accounts.minikube.createDeployment\" : true}"
Skipper includes the concept of platforms,
so it is important to define the "accounts" based on the project preferences. In the above YAML file, the accounts map
to |
If you’d like to change the version of Skipper server, you can do so by updating the image from |
If you’d like to orchestrate stream processing pipelines with Apache Kafka as the messaging middleware, you must change the value for
|
The resource for the Skipper service is shown below:
apiVersion: v1
kind: Service
metadata:
name: skipper
labels:
app: skipper
spec:
# If you are running k8s on a local dev box or using minikube, you can use type NodePort instead
type: LoadBalancer
ports:
- port: 80
targetPort: 7577 # port used by 'skpr' (i.e., 7577)
selector:
app: skipper
Run the following commands to start Skipper as the companion server for Spring Cloud Data Flow:
$ kubectl create -f src/kubernetes/skipper/skipper-deployment.yaml
$ kubectl create -f src/kubernetes/skipper/skipper-svc.yaml
You can use the command kubectl get all -l app=skipper
to verify that the deployment, pod and service resources are running.
Use the command kubectl delete all -l app=skipper
to clean up afterwards.
Use the kubectl get svc scdf-server
command to locate the EXTERNAL_IP address assigned to scdf-server
, we will use that
later to connect from the shell.
$ kubectl get svc
NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE
skipper 10.103.246.83 130.211.203.247 80/TCP 4m
So the URL you need to use is in this case is: 130.211.203.247
If you are using Minikube then you don’t have an external load balancer and the EXTERNAL-IP will show as <pending>
.
You need to use the NodePort assigned for the skipper
service. Use this command to look up the URL to use:
$ minikube service --url skipper
http://192.168.99.100:32060
2. Helm Installation
Spring Cloud DataFlow offers a Helm Chart for deploying the Spring Cloud Data Flow server and its required services to a Kubernetes Cluster.
The helm chart is currenlty only available for the 1.2 GA version of Data Flow for Kubernetes. |
The following instructions cover how to initialize Helm
and install Spring Cloud Data Flow on a Kubernetes cluster.
-
Installing Helm
Helm
is comprised of 2 components: one is the client (Helm) the other is the server (Tiller). TheHelm
client is run on your local machine and can be installed using the following instructions found here. If Tiller has not been installed on your cluster, execute the followingHelm
client command:$ helm init
To verify that the Tiller
pod is running execute the following command:kubectl get pod --namespace kube-system
and you should see theTiller
pod running. -
Installing the Spring Cloud Data Flow Server and required services.
Before we can run the Spring Cloud Data Flow Chart, we need to access the incubator repository where it currently resides. To add this repository to our
Helm
install, execute the following commands:helm repo add incubator https://kubernetes-charts-incubator.storage.googleapis.com helm repo update
To install Spring Cloud Data Flow and its required services execute the following:
helm install --name my-release incubator/spring-cloud-data-flow
If you are running on a cluster without a load balancer, such as Minikube, then you should override the service type to use NodePort. Add the
--set server.service.type=NodePort
override:helm install --name my-release --set server.service.type=NodePort \ incubator/spring-cloud-data-flow
If you wish specify a different version of Spring Cloud Data Flow besides the current release, you can set the
server.version
as shown below:helm install --name my-release incubator/spring-cloud-data-flow --set server.version=<version-you-want>
To see all of the settings that can be configured on the Spring Cloud Data Flow chart, check out the README. You should see the following output:
NAME: my-release LAST DEPLOYED: Tue Oct 3 10:33:50 2017 NAMESPACE: default STATUS: DEPLOYED RESOURCES: ==> v1/ConfigMap NAME DATA AGE my-release-data-flow-server 1 2s ==> v1/PersistentVolumeClaim NAME STATUS VOLUME CAPACITY ACCESSMODES STORAGECLASS AGE my-release-mysql Pending standard 2s my-release-rabbitmq Pending standard 2s my-release-redis Pending standard 2s ==> v1/Service NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE my-release-mysql 10.59.247.118 <none> 3306/TCP 2s my-release-rabbitmq 10.59.249.211 <none> 4369/TCP,5672/TCP,25672/TCP,15672/TCP 2s my-release-redis 10.59.242.108 <none> 6379/TCP 2s my-release-data-flow-metrics 10.59.247.121 <none> 80/TCP 2s my-release-data-flow-server 10.59.249.224 <pending> 80:30859/TCP 2s ==> v1beta1/Deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE my-release-mysql 1 1 1 0 2s my-release-rabbitmq 1 1 1 0 2s my-release-redis 1 1 1 0 2s my-release-data-flow-metrics 1 1 1 0 2s my-release-data-flow-server 1 1 1 0 1s ==> v1/Secret NAME TYPE DATA AGE my-release-mysql Opaque 2 2s my-release-rabbitmq Opaque 2 2s my-release-redis Opaque 1 2s my-release-data-flow Opaque 2 2s NOTES: 1. Get the application URL by running these commands: NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch the status of the server by running 'kubectl get svc -w my-release-data-flow-server' export SERVICE_IP=$(kubectl get svc --namespace default my-release-data-flow-server -o jsonpath='{.status.loadBalancer.ingress[0].ip}') echo http://$SERVICE_IP:80
You have just created a new release in the default namespace of your Kubernetes cluster. The notes section gives instructions for connecting to the newly installed server. It takes a couple of minutes for the application and its required services to start up. You can check on the status by issuing a
kubectl get pod -w
command. Wait for the READY column to show "1/1" for all pods. Once that is done, you can connect to the Data Flow server using the external ip listed via akubectl get svc my-release-data-flow-server
command. The default username isuser
, and the password ispassword
.If you are running on Minikube then you can use the following command to get the URL for the server:
minikube service --url my-release-data-flow-server
To see what
Helm
releases you have running, you can use thehelm list
command. When it is time to delete the release, runhelm delete my-release
. This removes any resources created for the release but keeps release information so you can rollback any changes using ahelm rollback my-release 1
command. To completely delete the release and purge any release metadata, usehelm delete my-release --purge
.There is an issue with generated secrets used for the required services getting rotated on chart upgrades. To avoid this set the password for these services when installing the chart. You can use:
helm install --name my-release \ --set rabbitmq.rabbitmqPassword=rabbitpwd \ --set mysql.mysqlRootPassword=mysqlpwd \ --set redis.redisPassword=redispwd incubator/spring-cloud-data-flow
3. Deploying Streams
3.1. Create Streams without Skipper
-
Download and run the Spring Cloud Data Flow shell.
wget http://repo.spring.io/milestone/org/springframework/cloud/spring-cloud-dataflow-shell/1.3.0.RC1/spring-cloud-dataflow-shell-1.3.0.RC1.jar $ java -jar spring-cloud-dataflow-shell-1.3.0.RC1.jar
That should give you the following startup message from the shell:
____ ____ _ __ / ___| _ __ _ __(_)_ __ __ _ / ___| | ___ _ _ __| | \___ \| '_ \| '__| | '_ \ / _` | | | | |/ _ \| | | |/ _` | ___) | |_) | | | | | | | (_| | | |___| | (_) | |_| | (_| | |____/| .__/|_| |_|_| |_|\__, | \____|_|\___/ \__,_|\__,_| ____ |_| _ __|___/ __________ | _ \ __ _| |_ __ _ | ___| | _____ __ \ \ \ \ \ \ | | | |/ _` | __/ _` | | |_ | |/ _ \ \ /\ / / \ \ \ \ \ \ | |_| | (_| | || (_| | | _| | | (_) \ V V / / / / / / / |____/ \__,_|\__\__,_| |_| |_|\___/ \_/\_/ /_/_/_/_/_/ 1.3.0.RC1 Welcome to the Spring Cloud Data Flow shell. For assistance hit TAB or type "help". server-unknown:>
Configure the Data Flow server URI with the following command (use the URL determined above in the previous step) using the default user and password settings:
server-unknown:>dataflow config server --username user --password password --uri http://130.211.203.246/ Successfully targeted http://130.211.203.246/ dataflow:>
-
Register the Docker with Rabbit binder versions of the
time
andlog
apps using the shell.dataflow:>app register --type source --name time --uri docker://springcloudstream/time-source-rabbit:1.3.0.RELEASE --metadata-uri maven://org.springframework.cloud.stream.app:time-source-rabbit:jar:metadata:1.3.0.RELEASE dataflow:>app register --type sink --name log --uri docker://springcloudstream/log-sink-rabbit:1.3.0.RELEASE --metadata-uri maven://org.springframework.cloud.stream.app:log-sink-rabbit:jar:metadata:1.3.0.RELEASE
-
Alternatively, if you would like to register all out-of-the-box stream applications built with the Rabbit binder in bulk, you can with the following command. For more details, review how to register applications.
dataflow:>app import --uri http://bit.ly/Celsius-GA-stream-applications-rabbit-docker
-
Deploy a simple stream in the shell
dataflow:>stream create --name ticktock --definition "time | log" --deploy
You can use the command
kubectl get pods
to check on the state of the pods corresponding to this stream. We can run this from the shell by running it as an OS command by adding a "!" before the command.dataflow:>! kubectl get pods -l role=spring-app command is:kubectl get pods -l role=spring-app NAME READY STATUS RESTARTS AGE ticktock-log-0-qnk72 1/1 Running 0 2m ticktock-time-r65cn 1/1 Running 0 2m
Look at the logs for the pod deployed for the log sink.
dataflow:>! kubectl logs ticktock-log-0-qnk72 command is:kubectl logs ticktock-log-0-qnk72 ... 2017-07-20 04:34:37.369 INFO 1 --- [time.ticktock-1] log-sink : 07/20/17 04:34:37 2017-07-20 04:34:38.371 INFO 1 --- [time.ticktock-1] log-sink : 07/20/17 04:34:38 2017-07-20 04:34:39.373 INFO 1 --- [time.ticktock-1] log-sink : 07/20/17 04:34:39 2017-07-20 04:34:40.380 INFO 1 --- [time.ticktock-1] log-sink : 07/20/17 04:34:40 2017-07-20 04:34:41.381 INFO 1 --- [time.ticktock-1] log-sink : 07/20/17 04:34:41
-
Destroy the stream
dataflow:>stream destroy --name ticktock
A useful command to help in troubleshooting issues, such as a container that has a fatal error starting up, add the options
--previous
to view last terminated container log. You can also get more detailed information about the pods by using thekubctl describe
like:kubectl describe pods/ticktock-log-qnk72
If you need to specify any of the app specific configuration properties then you might use "long-form" of them including the app specific prefix like --jdbc.tableName=TEST_DATA
. This form is required if you didn’t register the--metadata-uri
for the Docker based starter apps. In this case you will also not see the configuration properties listed when using theapp info
command or in the Dashboard GUI.
3.2. Create Streams with Skipper
Refer to the section Streams deployed using Skipper for more information.
3.3. Accessing app from outside the cluster
If you need to be able to connect to from outside of the Kubernetes cluster to an app that you deploy, like the http-source
, then you need to use either an external load balancer for the incoming connections or you need to use a NodePort configuration that will expose a proxy port on each Kubetnetes Node. If your cluster doesn’t support external load balancers, like the Minikube, then you must use the NodePort approach. You can use deployment properties for configuring the access. Use deployer.http.kubernetes.createLoadBalancer=true
for the app to specify that you want to have a LoadBalancer with an external IP address created for your app’s service. For the NodePort configuration use deployer.http.kubernetes.createNodePort=<port>
where <port>
should be a number between 30000 and 32767.
-
Register the
http-source
, you can use the following command:dataflow:>app register --type source --name http --uri docker:springcloudstream/http-source-rabbit:1.3.0.RELEASE --metadata-uri maven://org.springframework.cloud.stream.app:http-source-rabbit:jar:metadata:1.3.0.RELEASE
-
Create the
http | log
stream without deploying it using the following command:dataflow:>stream create --name test --definition "http | log"
-
If your cluster supports an External LoadBalancer for the
http-source
, then you can use the following command to deploy the stream:dataflow:>stream deploy test --properties "deployer.http.kubernetes.createLoadBalancer=true"
Wait for the pods to be started showing 1/1 in the READY column by using this command:
dataflow:>! kubectl get pods -l role=spring-app command is:kubectl get pods -l role=spring-app NAME READY STATUS RESTARTS AGE test-http-2bqx7 1/1 Running 0 3m test-log-0-tg1m4 1/1 Running 0 3m
Now, look up the external IP address for the
http
app (it can sometimes take a minute or two for the external IP to get assigned):dataflow:>! kubectl get service test-http command is:kubectl get service test-http NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE test-http 10.103.251.157 130.211.200.96 8080/TCP 58s
-
If you are using Minikube, or any cluster that doesn’t support an External LoadBalancer, then you should deploy the stream with a NodePort in the range of 30000-32767. Use the following command to deploy it:
dataflow:>stream deploy test --properties "deployer.http.kubernetes.createNodePort=32123"
Wait for the pods to be started showing 1/1 in the READY column by using this command:
dataflow:>! kubectl get pods -l role=spring-app command is:kubectl get pods -l role=spring-app NAME READY STATUS RESTARTS AGE test-http-9obkq 1/1 Running 0 3m test-log-0-ysiz3 1/1 Running 0 3m
Now look up the URL to use with the following command:
dataflow:>! minikube service --url test-http command is:minikube service --url test-http http://192.168.99.100:32123
-
Post some data to the
test-http
app either using the EXTERNAL-IP address from above with port 8080 or the URL provided by the minikube command:dataflow:>http post --target http://130.211.200.96:8080 --data "Hello"
-
Finally, look at the logs for the
test-log
pod:dataflow:>! kubectl get pods-l role=spring-app command is:kubectl get pods-l role=spring-app NAME READY STATUS RESTARTS AGE test-http-9obkq 1/1 Running 0 2m test-log-0-ysiz3 1/1 Running 0 2m dataflow:>! kubectl logs test-log-0-ysiz3 command is:kubectl logs test-log-0-ysiz3 ... 2016-04-27 16:54:29.789 INFO 1 --- [ main] o.s.c.s.b.k.KafkaMessageChannelBinder$3 : started inbound.test.http.test 2016-04-27 16:54:29.799 INFO 1 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 2016-04-27 16:54:29.799 INFO 1 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147482647 2016-04-27 16:54:29.895 INFO 1 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2016-04-27 16:54:29.896 INFO 1 --- [ kafka-binder-] log.sink : Hello
-
Destroy the stream
dataflow:>stream destroy --name test
4. Deploying Tasks
-
Create a task and launch it
Let’s register the
timestamp
task app and create a simple task definition and launch it.dataflow:>app register --type task --name timestamp --uri docker:springcloudtask/timestamp-task:1.3.0.RELEASE --metadata-uri maven://org.springframework.cloud.task.app:timestamp-task:jar:metadata:1.3.0.RELEASE dataflow:>task create task1 --definition "timestamp" dataflow:>task launch task1
We can now list the tasks and executions using these commands:
dataflow:>task list ╔═════════╤═══════════════╤═══════════╗ ║Task Name│Task Definition│Task Status║ ╠═════════╪═══════════════╪═══════════╣ ║task1 │timestamp │running ║ ╚═════════╧═══════════════╧═══════════╝ dataflow:>task execution list ╔═════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗ ║Task Name│ID│ Start Time │ End Time │Exit Code║ ╠═════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣ ║task1 │1 │Fri May 05 18:12:05 EDT 2017│Fri May 05 18:12:05 EDT 2017│0 ║ ╚═════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝
-
Destroy the task
dataflow:>task destroy --name task1
5. Application Configuration
This section covers how you can customize the deployment of your applications. You can use a number of deployer properties to influence settings for the applications that are deployed.
See KubernetesDeployerProperties for more of the supported options.
If you would like to override the default values for all apps that you deploy then you should modify the Spring Cloud Deployer for Kubernetes Properties for the server.
5.1. Memory and CPU Settings
The apps are deployed by default with the following "Limits" and "Requests" settings:
Limits:
cpu: 500m
memory: 512Mi
Requests:
cpu: 500m
memory: 512Mi
You might find that the 512Mi memory limit is too low and to increase it you can provide a common spring.cloud.deployer.memory
deployer property like this (replace <app> with the name of the app you would like to set this for):
deployer.<app>.memory=640m
This property affects bot the Requests and Limits memory value set for the container.
If you would like to set the Requests and Limits values separately you would have to use the deployer properties that are specific to the Kubernetes deployer. To set the Limits to 1000m for cpu, 1024Mi for memory and Requests to 800m for cpu, 640Mi for memory you can use the following properties:
deployer.<app>.kubernetes.limits.cpu=1000m
deployer.<app>.kubernetes.limits.memory=1024Mi
deployer.<app>.kubernetes.requests.cpu=800m
deployer.<app>.kubernetes.requests.memory=640Mi
That should result in the following container settings being used:
Limits:
cpu: 1
memory: 1Gi
Requests:
cpu: 800m
memory: 640Mi
When using the common memory property you should use and m suffix for the value while when using the Kubernetes specific properties you should use the Kubernetes Mi style suffix.
|
The settings we have used so far only affect the settings for the container, they do not affect the memory setting for the JVM process in the container. If you would like to set JVM memory settings you can provide an environment variable for this, see the next section for details.
5.2. Environment Variables
To influence the environment settings for a given app, you can take advantage of the spring.cloud.deployer.kubernetes.environmentVariables
deployer property.
For example, a common requirement in production settings is to influence the JVM memory arguments.
This can be achieved by using the JAVA_TOOL_OPTIONS
environment variable:
deployer.<app>.kubernetes.environmentVariables=JAVA_TOOL_OPTIONS=-Xmx1024m
The environmentVariables property accepts a comma delimited string. If an environment variable contains a value
which is also a comma delimited string, then it must be enclosed in single quotes, e.g.,
spring.cloud.deployer.kubernetes.environmentVariables=spring.cloud.stream.kafka.binder.brokers='somehost:9092,
anotherhost:9093'
|
This overrides the JVM memory setting for the desired <app> (just replace <app> with the name of your app).
5.3. Liveness and Readiness Probes
The liveness and readiness probes are using the paths \health
and \info
respectively. They use a delay of 10 for both and a period of 60 and 10 respectively. You can chage these defaults when you deploy by using deployer properties.
Here is an example changing the liveness probe (just replace <app> with the name of your app):
deployer.<app>.kubernetes.livenessProbePath=/info
deployer.<app>.kubernetes.livenessProbeDelay=120
deployer.<app>.kubernetes.livenessProbePeriod=20
Similarly, swap liveness for readiness to override the default readiness settings.
Applications
A selection of pre-built stream and task/batch starter apps for various data integration and processing scenarios facilitate learning and experimentation. For more details, review how to register applications
Architecture
6. Introduction
Spring Cloud Data Flow simplifies the development and deployment of applications focused on data processing use-cases. The major concepts of the architecture are Applications, the Data Flow Server, and the target runtime.
Applications come in two flavors
-
Long lived Stream applications where an unbounded amount of data is consumed or produced via messaging middleware.
-
Short lived Task applications that process a finite set of data and then terminate.
Depending on the runtime, applications can be packaged in two ways
-
Spring Boot uber-jar that is hosted in a maven repository, file, http or any other Spring resource implementation.
-
Docker
The runtime is the place where applications execute. The target runtimes for applications are platforms that you may already be using for other application deployments.
The supported runtimes are
-
Cloud Foundry
-
Apache YARN
-
Kubernetes
-
Apache Mesos
-
Local Server for development
There is a deployer Service Provider Interface (SPI) that enables you to extend Data Flow to deploy onto other runtimes, for example to support Docker Swarm. There are community implementations of Hashicorp’s Nomad and RedHat Openshift is available. We look forward to working with the community for further contributions!
The component that is responsible for deploying applications to a runtime is the Data Flow Server. There is a Data Flow Server executable jar provided for each of the target runtimes. The Data Flow server is responsible for:
-
Interpreting and executing a stream DSL that describes the logical flow of data through multiple long lived applications.
-
Launching a long lived task application
-
Interpreting and executing a composed task DSL that describes the logical flow of data through multiple short lived applications.
-
Applyhing a deployment manifest that describes the mapping of applications onto the runtime. For example, to set the initial number of instances, memory requirements, and data partitioning.
-
Providing the runtime status of deployed applications
As an example, the stream DSL to describe the flow of data from an http source to an Apache Cassandra sink would be written as “http | cassandra”. These names in the DSL are registered with the Data Flow Server and map onto application artifacts that can be hosted in Maven or Docker repositories. Many source, processor, and sink applications for common use-cases (e.g. jdbc, hdfs, http, router) are provided by the Spring Cloud Data Flow team. The pipe symbol represents the communication between the two applications via messaging middleware. The two messaging middleware brokers that are supported are
-
Apache Kafka
-
RabbitMQ
In the case of Kafka, when deploying the stream, the Data Flow server is responsible to create the topics that correspond to each pipe symbol and configure each application to produce or consume from the topics so the desired flow of data is achieved.
The interaction of the main components is shown below
In this diagram a DSL description of a stream is POSTed to the Data Flow Server. Based on the mapping of DSL application names to Maven and Docker artifacts, the http-source and cassandra-sink applications are deployed on the target runtime.
7. Microservice Architectural Style
The Data Flow Server deploys applications onto the target runtime that conform to the microservice architectural style. For example, a stream represents a high level application that consists of multiple small microservice applications each running in their own process. Each microservice application can be scaled up or down independent of the other and each has their own versioning lifecycle.
Both Streaming and Task based microservice applications build upon Spring Boot as the foundational library. This gives all microservice applications functionality such as health checks, security, configurable logging, monitoring and management functionality, as well as executable JAR packaging.
It is important to emphasise that these microservice applications are ‘just apps’ that you can run by yourself using ‘java -jar’ and passing in appropriate configuration properties. We provide many common microservice applications for common operations so you don’t have to start from scratch when addressing common use-cases which build upon the rich ecosystem of Spring Projects, e.g Spring Integration, Spring Data, Spring Hadoop and Spring Batch. Creating your own microservice application is similar to creating other Spring Boot applications, you can start using the Spring Initialzr web site or the UI to create the basic scaffolding of either a Stream or Task based microservice.
In addition to passing in the appropriate configuration to the applications, the Data Flow server is responsible for preparing the target platform’s infrastructure so that the application can be deployed. For example, in Cloud Foundry it would be binding specified services to the applications and executing the ‘cf push’ command for each application. For Kubernetes it would be creating the replication controller, service, and load balancer.
The Data Flow Server helps simplify the deployment of multiple applications onto a target runtime, but one could also opt to deploy each of the microservice applications manually and not use Data Flow at all. This approach might be more appropriate to start out with for small scale deployments, gradually adopting the convenience and consistency of Data Flow as you develop more applications. Manual deployment of Stream and Task based microservices is also a useful educational exercise that will help you better understand some of the automatic applications configuration and platform targeting steps that the Data Flow Server provides.
7.1. Comparison to other Platform architectures
Spring Cloud Data Flow’s architectural style is different than other Stream and Batch processing platforms. For example in Apache Spark, Apache Flink, and Google Cloud Dataflow applications run on a dedicated compute engine cluster. The nature of the compute engine gives these platforms a richer environment for performing complex calculations on the data as compared to Spring Cloud Data Flow, but it introduces complexity of another execution environment that is often not needed when creating data centric applications. That doesn’t mean you cannot do real time data computations when using Spring Cloud Data Flow. Refer to the analytics section which describes the integration of Redis to handle common counting based use-cases as well as the RxJava integration for functional API driven analytics use-cases, such as time-sliding-window and moving-average among others.
Similarly, Apache Storm, Hortonworks DataFlow and Spring Cloud Data Flow’s predecessor, Spring XD, use a dedicated application execution cluster, unique to each product, that determines where your code should execute on the cluster and perform health checks to ensure that long lived applications are restarted if they fail. Often, framework specific interfaces are required to be used in order to correctly “plug in” to the cluster’s execution framework.
As we discovered during the evolution of Spring XD, the rise of multiple container frameworks in 2015 made creating our own runtime a duplication of efforts. There is no reason to build your own resource management mechanics, when there are multiple runtime platforms that offer this functionality already. Taking these considerations into account is what made us shift to the current architecture where we delegate the execution to popular runtimes, runtimes that you may already be using for other purposes. This is an advantage in that it reduces the cognitive distance for creating and managing data centric applications as many of the same skills used for deploying other end-user/web applications are applicable.
8. Streaming Applications
While Spring Boot provides the foundation for creating DevOps friendly microservice applications, other libraries in the Spring ecosystem help create Stream based microservice applications. The most important of these is Spring Cloud Stream.
The essence of the Spring Cloud Stream programming model is to provide an easy way to describe multiple inputs and outputs of an application that communicate over messaging middleware. These input and outputs map onto Kafka topics or Rabbit exchanges and queues. Common application configuration for a Source that generates data, a Process that consumes and produces data and a Sink that consumes data is provided as part of the library.
8.1. Imperative Programming Model
Spring Cloud Stream is most closely integrated with Spring Integration’s imperative "event at a time" programming model. This means you write code that handles a single event callback. For example,
@EnableBinding(Sink.class)
public class LoggingSink {
@StreamListener(Sink.INPUT)
public void log(String message) {
System.out.println(message);
}
}
In this case the String payload of a message coming on the input channel, is handed to the log method. The @EnableBinding
annotation is what is used to tie together the input channel to the external middleware.
8.2. Functional Programming Model
However, Spring Cloud Stream can support other programming styles. The use of reactive APIs where incoming and outgoing data is handled as continuous data flows and it defines how each individual message should be handled. You can also use operators that describe functional transformations from inbound to outbound data flows. The upcoming versions will support Apache Kafka’s KStream API in the programming model.
9. Streams
9.1. Topologies
The Stream DSL describes linear sequences of data flowing through the system. For example, in the stream definition http | transformer | cassandra
, each pipe symbol connects the application on the left to the one on the right. Named channels can be used for routing and to fan out data to multiple messaging destinations.
Taps can be used to ‘listen in’ to the data that if flowing across any of the pipe symbols. Taps can be used as sources for new streams with an in independent life cycle.
9.2. Concurrency
For an application that will consume events, Spring Cloud stream exposes a concurrency setting that controls the size of a thread pool used for dispatching incoming messages. See the {spring-cloud-stream-docs}#_consumer_properties[Consumer properties] documentation for more information.
9.3. Partitioning
A common pattern in stream processing is to partition the data as it moves from one application to the next. Partitioning is a critical concept in stateful processing, for either performance or consistency reasons, to ensure that all related data is processed together. For example, in a time-windowed average calculation example, it is important that all measurements from any given sensor are processed by the same application instance. Alternatively, you may want to cache some data related to the incoming events so that it can be enriched without making a remote procedure call to retrieve the related data.
Spring Cloud Data Flow supports partitioning by configuring Spring Cloud Stream’s output and input bindings. Spring Cloud Stream provides a common abstraction for implementing partitioned processing use cases in a uniform fashion across different types of middleware. Partitioning can thus be used whether the broker itself is naturally partitioned (e.g., Kafka topics) or not (e.g., RabbitMQ). The following image shows how data could be partitioned into two buckets, such that each instance of the average processor application consumes a unique set of data.
To use a simple partitioning strategy in Spring Cloud Data Flow, you only need set the instance count for each application in the stream and a partitionKeyExpression
producer property when deploying the stream. The partitionKeyExpression
identifies what part of the message will be used as the key to partition data in the underlying middleware. An ingest
stream can be defined as http | averageprocessor | cassandra
(Note that the Cassandra sink isn’t shown in the diagram above). Suppose the payload being sent to the http source was in JSON format and had a field called sensorId
. Deploying the stream with the shell command stream deploy ingest --propertiesFile ingestStream.properties
where the contents of the file ingestStream.properties
are
deployer.http.count=3
deployer.averageprocessor.count=2
app.http.producer.partitionKeyExpression=payload.sensorId
will deploy the stream such that all the input and output destinations are configured for data to flow through the applications but also ensure that a unique set of data is always delivered to each averageprocessor instance. In this case the default algorithm is to evaluate payload.sensorId % partitionCount
where the partitionCount
is the application count in the case of RabbitMQ and the partition count of the topic in the case of Kafka.
Please refer to Passing stream partition properties for additional strategies to partition streams during deployment and how they map onto the underlying {spring-cloud-stream-docs}#_partitioning[Spring Cloud Stream Partitioning properties].
Also note, that you can’t currently scale partitioned streams. Read the section Scaling at runtime for more information.
9.4. Message Delivery Guarantees
Streams are composed of applications that use the Spring Cloud Stream library as the basis for communicating with the underlying messaging middleware product. Spring Cloud Stream also provides an opinionated configuration of middleware from several vendors, in particular providing {spring-cloud-stream-docs}#_persistent_publish_subscribe_support[persistent publish-subscribe semantics].
The {spring-cloud-stream-docs}#_binders[Binder abstraction] in Spring Cloud Stream is what connects the application to the middleware. There are several configuration properties of the binder that are portable across all binder implementations and some that are specific to the middleware.
For consumer applications there is a retry policy for exceptions generated during message handling. The retry policy is configured using the {spring-cloud-stream-docs}#_consumer_properties[common consumer properties] maxAttempts
, backOffInitialInterval
, backOffMaxInterval
, and backOffMultiplier
. The default values of these properties will retry the callback method invocation 3 times and wait one second for the first retry. A backoff multiplier of 2 is used for the second and third attempts.
When the number of retry attempts has exceeded the maxAttempts
value, the exception and the failed message will become the payload of a message and be sent to the application’s error channel. By default, the default message handler for this error channel logs the message. You can change the default behavior in your application by creating your own message handler that subscribes to the error channel.
Spring Cloud Stream also supports a configuration option for both Kafka and RabbitMQ binder implementations that will send the failed message and stack trace to a dead letter queue. The dead letter queue is a destination and its nature depends on the messaging middleware (e.g in the case of Kafka it is a dedicated topic). To enable this for RabbitMQ set the {spring-cloud-stream-docs}#_rabbitmq_consumer_properties[consumer properties] republishtoDlq
and autoBindDlq
and the {spring-cloud-stream-docs}#_rabbit_producer_properties[producer property] autoBindDlq
to true when deploying the stream. To always apply these producer and consumer properties when deploying streams, configure them as common application properties when starting the Data Flow server.
Additional messaging delivery guarantees are those provided by the underlying messaging middleware that is chosen for the application for both producing and consuming applications. Refer to the Kafka {spring-cloud-stream-docs}#_kafka_consumer_properties[Consumer] and {spring-cloud-stream-docs}#_kafka_producer_properties[Producer] and Rabbit {spring-cloud-stream-docs}#_rabbitmq_consumer_properties[Consumer] and {spring-cloud-stream-docs}#_rabbit_producer_properties[Producer] documentation for more details. You will find extensive declarative support for all the native QOS options.
10. Analytics
Spring Cloud Data Flow is aware of certain Sink applications that will write counter data to Redis and provides an REST endpoint to read counter data. The types of counters supported are
-
Counter - Counts the number of messages it receives, optionally storing counts in a separate store such as redis.
-
Field Value Counter - Counts occurrences of unique values for a named field in a message payload
-
Aggregate Counter - Stores total counts but also retains the total count values for each minute, hour day and month.
It is important to note that the timestamp that is used in the aggregate counter can come from a field in the message itself so that out of order messages are properly accounted.
11. Task Applications
The Spring Cloud Task programming model provides:
-
Persistence of the Task’s lifecycle events and exit code status.
-
Lifecycle hooks to execute code before or after a task execution.
-
Emit task events to a stream (as a source) during the task lifecycle.
-
Integration with Spring Batch Jobs.
12. Data Flow Server
12.1. Endpoints
The Data Flow Server uses an embedded servlet container and exposes REST endpoints for creating, deploying, undeploying, and destroying streams and tasks, querying runtime state, analytics, and the like. The Data Flow Server is implemented using Spring’s MVC framework and the Spring HATEOAS library to create REST representations that follow the HATEOAS principle.
12.2. Customization
Each Data Flow Server executable jar targets a single runtime by delegating to the implementation of the deployer Service Provider Interface found on the classpath.
We provide a Data Flow Server executable jar that targets a single runtime. The Data Flow server delegates to the implementation of the deployer Service Provider Interface found on the classpath. In the current version, there are no endpoints specific to a target runtime, but may be available in future releases as a convenience to access runtime specific features
While we provide a server executable for each of the target runtimes you can also create your own customized server application using Spring Initialzr. This let’s you add or remove functionality relative to the executable jar we provide. For example, adding additional security implementations, custom endpoints, or removing Task or Analytics REST endpoints. You can also enable or disable some features through the use of feature toggles.
12.3. Security
The Data Flow Server executable jars support basic http, LDAP(S), File-based, and OAuth 2.0 authentication to access its endpoints. Refer to the security section for more information.
Authorization via groups is planned for a future release.
13. Runtime
13.1. Fault Tolerance
The target runtimes supported by Data Flow all have the ability to restart a long lived application should it fail. Spring Cloud Data Flow sets up whatever health probe is required by the runtime environment when deploying the application.
The collective state of all applications that comprise the stream is used to determine the state of the stream. If an application fails, the state of the stream will change from ‘deployed’ to ‘partial’.
13.2. Resource Management
Each target runtime lets you control the amount of memory, disk and CPU that is allocated to each application. These are passed as properties in the deployment manifest using key names that are unique to each runtime. Refer to the each platforms server documentation for more information.
13.3. Scaling at runtime
When deploying a stream, you can set the instance count for each individual application that comprises the stream. Once the stream is deployed, each target runtime lets you control the target number of instances for each individual application. Using the APIs, UIs, or command line tools for each runtime, you can scale up or down the number of instances as required. Future work will provide a portable command in the Data Flow Server to perform this operation.
Currently, this is not supported with the Kafka binder (based on the 0.8 simple consumer at the time of the release), as well as partitioned streams, for which the suggested workaround is redeploying the stream with an updated number of instances. Both cases require a static consumer set up based on information about the total instance count and current instance index, a limitation intended to be addressed in future releases. For example, Kafka 0.9 and higher provides good infrastructure for scaling applications dynamically and will be available as an alternative to the current Kafka 0.8 based binder in the near future. One specific concern regarding scaling partitioned streams is the handling of local state, which is typically reshuffled as the number of instances is changed. This is also intended to be addressed in the future versions, by providing first class support for local state management.
13.4. Application Versioning
Application versioning, that is upgrading or downgrading an application from one version to another, is not directly supported by Spring Cloud Data Flow. You must rely on specific target runtime features to perform these operational tasks.
The roadmap for Spring Cloud Data Flow will deploy applications that are compatible with Spinnaker to manage the complete application lifecycle. This also includes automated canary analysis backed by application metrics. Portable commands in the Data Flow server to trigger pipelines in Spinnaker are also planned.
Server Configuration
In this section you will learn how to configure Spring Cloud Data Flow server’s features such as the relational database to use and security.
14. Feature Toggles
Data Flow server offers specific set of features that can be enabled/disabled when launching. These features include all the lifecycle operations, REST endpoints (server, client implementations including Shell and the UI) for:
-
Streams
-
Tasks
-
Analytics
You can enable or disable these features by setting the following boolean environment variables when launching the Data Flow server:
-
SPRING_CLOUD_DATAFLOW_FEATURES_STREAMS_ENABLED
-
SPRING_CLOUD_DATAFLOW_FEATURES_TASKS_ENABLED
-
SPRING_CLOUD_DATAFLOW_FEATURES_ANALYTICS_ENABLED
By default, all the features are enabled.
Since analytics feature is enabled by default, the Data Flow server is expected to have a valid Redis store available as analytic repository as we provide a default implementation of analytics based on Redis. This also means that the Data Flow server’s health depends on the redis store availability as well. If you do not want to enable HTTP endpoints to read analytics data written to Redis, then disable the analytics feature using the property mentioned above.
|
The REST endpoint /features
provides information on the features enabled/disabled.
15. General Configuration
The Spring Cloud Data Flow server for Kubernetes uses the Fabric8 spring-cloud-kubernetes
module to process both ConfigMap and Secrets settings. You just need to enable the ConfigMap support by passing in an environment variable of SPRING_CLOUD_KUBERNETES_CONFIG_NAME
and setting that to the name of the ConfigMap. Same is true for the Secrets where the environment variable is SPRING_CLOUD_KUBERNETES_SECRETS_NAME
. To use the Secrets you also need to set SPRING_CLOUD_KUBERNETES_SECRETS_ENABLE_API
to true.
Here is an example of a snippet from a deployment that sets these environment variables.
env:
- name: SPRING_CLOUD_KUBERNETES_SECRETS_ENABLE_API
value: 'true'
- name: SPRING_CLOUD_KUBERNETES_SECRETS_NAME
value: mysql
- name: SPRING_CLOUD_KUBERNETES_CONFIG_NAME
value: scdf-server
15.1. Using ConfigMap and Secrets
Configuration properties can be passed to the Data Flow Server using Kubernetes ConfigMap and Secrets.
An example configuration could look like the following where we configure Rabbit MQ, MySQL and Redis as well as basic security settings for the server:
apiVersion: v1
kind: ConfigMap
metadata:
name: scdf-server
labels:
app: scdf-server
data:
application.yaml: |-
security:
basic:
enabled: true
realm: Spring Cloud Data Flow
spring:
cloud:
dataflow:
security:
authentication:
file:
enabled: true
users:
admin: admin, ROLE_MANAGE, ROLE_VIEW
user: password, ROLE_VIEW, ROLE_CREATE
deployer:
kubernetes:
environmentVariables: 'SPRING_RABBITMQ_HOST=${RABBITMQ_SERVICE_HOST},SPRING_RABBITMQ_PORT=${RABBITMQ_SERVICE_PORT},SPRING_REDIS_HOST=${REDIS_SERVICE_HOST},SPRING_REDIS_PORT=${REDIS_SERVICE_PORT}'
datasource:
url: jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT}/mysql
username: root
password: ${mysql-root-password}
driverClassName: org.mariadb.jdbc.Driver
testOnBorrow: true
validationQuery: "SELECT 1"
redis:
host: ${REDIS_SERVICE_HOST}
port: ${REDIS_SERVICE_PORT}
We assume here that Rabbit MQ is deployed using rabbitmq
as the service name. For MySQL we assume the service name is mysql
and for Redis we assume it is redis
. Kubernetes will publish these services' host and port values as environment variables that we can use when configuring the apps we deploy.
We prefer to provide the MySQL connection password in a Secrets file:
apiVersion: v1
kind: Secret
metadata:
name: mysql
labels:
app: mysql
data:
mysql-root-password: eW91cnBhc3N3b3Jk
The password is provided as a base64 encoded value.
16. Database Configuration
Spring Cloud Data Flow provides schemas for H2, HSQLDB, MySQL, Oracle, PostgreSQL, DB2 and SQL Server that will be automatically created when the server starts.
The JDBC drivers for MySQL (via MariaDB driver), HSQLDB, PostgreSQL along with embedded H2 are available out of the box. If you are using any other database, then the corresponding JDBC driver jar needs to be on the classpath of the server.
For instance, If you are using MySQL in addition to password in the Secrets file provide the following properties in the ConfigMap:
data:
application.yaml: |-
spring:
datasource:
url: jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT}/mysql
username: root
password: ${mysql-root-password}
driverClassName: org.mariadb.jdbc.Driver
url: jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT}/test
driverClassName: org.mariadb.jdbc.Driver
For PostgreSQL:
data:
application.yaml: |-
spring:
datasource:
url: jdbc:postgresql://${PGSQL_SERVICE_HOST}:${PGSQL_SERVICE_PORT}/database
username: root
password: ${postgres-password}
driverClassName: org.postgresql.Driver
For HSQLDB:
data:
application.yaml: |-
spring:
datasource:
url: jdbc:hsqldb:hsql://${HSQLDB_SERVICE_HOST}:${HSQLDB_SERVICE_PORT}/database
username: sa
driverClassName: org.hsqldb.jdbc.JDBCDriver
There is a schema update to the Spring Cloud Data Flow datastore when upgrading from version 1.0.x to 1.1.x and from 1.1.x to 1.2.x .
Migration scripts for specific database types can be found in the spring-cloud-task repo.
|
17. Security
We are now securing the server application in the sample configurations file used in the Getting Started section.
This section covers the basic configuration settings we provide in the provided sample configuration, please refer to the core security documentation for more detailed coverage of the security configuration options for the Spring Cloud Data Flow server and shell.
The security settings in the src/kubernetes/server/server-config-rabbit.yaml
file are:
security:
basic:
enabled: true (1)
realm: Spring Cloud Data Flow (2)
spring:
cloud:
dataflow:
security:
authentication:
file:
enabled: true
users:
admin: admin, ROLE_MANAGE, ROLE_VIEW (3)
user: password, ROLE_VIEW, ROLE_CREATE (4)
1 | Enable security |
2 | Optionally set the realm, defaults to "Spring" |
3 | Create an 'admin' user with password set to 'admin' that can view apps, streams and tasks and that can also view management endpoints |
4 | Create a 'user' user with password set to 'password' than can register apps and create streams and tasks and also view them |
Feel free to change user names and passwords to suite, and also maybe move the definition of user passwords to a Kubernetes Secret.
18. Spring Cloud Deployer for Kubernetes Properties
The Spring Cloud Deployer for Kubernetes has several properties you can use to configure the apps that it deploys.
The configuration is controlled by configuration properties under the spring.cloud.deployer.kubernetes
prefix.
18.1. Using Deployments
The deployer uses Replication Controllers by default. To use Deployments instead you can set the following option as part of the container env section in a deployment YAML file. This is now the preferred setting and will be the default in future releases of the deployer.
env:
- name: SPRING_CLOUD_DEPLOYER_KUBERNETES_CREATE_DEPLOYMENT
value: 'true'
18.2. CPU and Memory Limits
You can control the default values to set the cpu
and memory
requirements for the pods that are created as part of app deployments. You can declare the following as part of the container env section in a deployment YAML file:
env:
- name: SPRING_CLOUD_DEPLOYER_KUBERNETES_CPU
value: 500m
- name: SPRING_CLOUD_DEPLOYER_KUBERNETES_MEMORY
value: 640Mi
18.3. Liveness and Rediness Probes Configurations
You can modify the settings used for the liveness and readiness probes. This might be necessary if your cluster is slower and the apps need more time to start up. Here is an example of setting the delay and period for the liveness probe:
env:
- name: SPRING_CLOUD_DEPLOYER_KUBERNETES_LIVENESS_PROBE_DELAY
value: '120'
- name: SPRING_CLOUD_DEPLOYER_KUBERNETES_LIVENESS_PROBE_PERIOD
value: '45'
See KubernetesDeployerProperties for more of the supported options.
18.4. Using SPRING_APPLICATION_JSON
Data Flow Server properties that are common across all of the Data Flow Server implementations including the configuration of maven repository settings can be set in a similar manner although the latter might be easier to set using a SPRING_APPLICATION_JSON
environment variable like:
env:
- name: SPRING_APPLICATION_JSON
value: "{ \"maven\": { \"local-repository\": null, \"remote-repositories\": { \"repo1\": { \"url\": \"https://repo.spring.io/libs-snapshot\"} } } }"
19. Monitoring and Management
We recommend using the kubectl
command for troubleshooting streams and tasks.
You can list all artifacts and resources used by using the following command:
kubectl get all,cm,secrets,pvc
You can list all resources used by a specific app or service by using a label to select resources. The following command list all resources used by the mysql
service:
kubectl get all -l app=mysql
You can get the logs for a specific pod by issuing:
kubectl logs pod <pod-name>
If the pod is continuously getting restarted you can add -p
as an option to see the previous log like:
kubectl logs -p <pod-name>
You can also tail or follow a log by adding an -f
option:
kubectl logs -f <pod-name>
A useful command to help in troubleshooting issues, such as a container that has a fatal error starting up, is to use the describe command like:
kubectl describe pod ticktock-log-0-qnk72
19.1. Inspecting Server Logs
You can access the server logs by using the following command (just supply the name of pod for the server):
kubectl get pod -l app=scdf=server
kubectl logs <scdf-server-pod-name>
19.2. Streams
The stream apps are deployed with the stream name followed by the name of the app and for processors and sinks there is also an instance index appended.
To see all the pods that are deployed by the Spring Cloud Data Flow server you can specify the label role=spring-app
:
kubectl get pod -l role=spring-app
To see details for a specific app deployment you can use (just supply the name of pod for the app):
kubectl describe pod <app-pod-name>
For the application logs use:
kubectl logs <app-pod-name>
If you would like to tail a log you can use:
kubectl logs -f <app-pod-name>
19.3. Tasks
Tasks are launched as bare pods without a replication controller. The pods remain after the tasks complete and this gives you an opportunity to review the logs.
To see all pods for a specific task use this command while providing the task name:
kubectl get pod -l task-name=<task-name>
To review the task logs use:
kubectl logs <task-pod-name>
You have two options to delete completed pods. You can delete them manually once they are no longer needed.
To delete the task pod use:
kubectl delete pod <task-pod-name>
You can also use the Data Flow shell command task execution cleanup
command to remove the completed pod for a task execution.
First we need to determine the ID
for the task execution:
dataflow:>task execution list
╔═════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗
║Task Name│ID│ Start Time │ End Time │Exit Code║
╠═════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣
║task1 │1 │Fri May 05 18:12:05 EDT 2017│Fri May 05 18:12:05 EDT 2017│0 ║
╚═════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝
Next we issue the command to cleanup the execution artifacts (the completed pod):
dataflow:>task execution cleanup --id 1
Request to clean up resources for task execution 1 has been submitted
Shell
In this section you will learn about the options for starting the Shell and more advanced functionality relating to how it handles white spaces, quotes, and interpretation of SpEL expressions. The introductory chapters to the Stream DSL and Composed Task DSL is a good place to start for the most common usage of shell commands.
20. Shell Options
The Shell is built upon the Spring Shell project. There are command line options generic to Spring Shell and some specific to Data Flow. The shell takes the following command line options
unix:>java -jar spring-cloud-dataflow-shell-1.2.1.RELEASE.jar --help
Data Flow Options:
--dataflow.uri=<uri> Address of the Data Flow Server [default: http://localhost:9393].
--dataflow.username=<USER> Username of the Data Flow Server [no default].
--dataflow.password=<PASSWORD> Password of the Data Flow Server [no default].
--dataflow.credentials-provider-command=<COMMAND> Executes an external command which must return an OAuth Access Token [no default].
--dataflow.skip-ssl-validation=<true|false> Accept any SSL certificate (even self-signed) [default: no].
--spring.shell.historySize=<SIZE> Default size of the shell log file [default: 3000].
--spring.shell.commandFile=<FILE> Data Flow Shell executes commands read from the file(s) and then exits.
--help This message.
The spring.shell.commandFile
option is of note, as it can be used to point to an existing file which contains
all the shell commands to deploy one or many related streams and tasks. This is useful when creating some scripts to
help automate the deployment.
There is also a shell command
dataflow:>script --file <YOUR_AWESOME_SCRIPT>
This is useful to help modularize a complex script into multiple indepenent files.
21. Listing available commands
Typing help
at the command prompt will give a listing of all available commands.
Most of the commands are for Data Flow functionality, but a few are general purpose.
! - Allows execution of operating system (OS) commands
clear - Clears the console
cls - Clears the console
date - Displays the local date and time
exit - Exits the shell
http get - Make GET request to http endpoint
http post - POST data to http endpoint
quit - Exits the shell
system properties - Shows the shell's properties
version - Displays shell version
Adding the name of the command to help
will display additional information on how to invoke the command.
dataflow:>help stream create
Keyword: stream create
Description: Create a new stream definition
Keyword: ** default **
Keyword: name
Help: the name to give to the stream
Mandatory: true
Default if specified: '__NULL__'
Default if unspecified: '__NULL__'
Keyword: definition
Help: a stream definition, using the DSL (e.g. "http --port=9000 | hdfs")
Mandatory: true
Default if specified: '__NULL__'
Default if unspecified: '__NULL__'
Keyword: deploy
Help: whether to deploy the stream immediately
Mandatory: false
Default if specified: 'true'
Default if unspecified: 'false'
22. Tab Completion
The shell command options can be completed in the shell by hitting the TAB
key after the leading --
. For example, hitting TAB
after stream create --
results in
dataflow:>stream create --
stream create --definition stream create --name
If you type --de
and then hit tab, --definition
will be expanded.
Tab completion is also available inside the stream or composed task DSL expression for application or task properties. You can also use TAB
to get hints in a stream DSL expression for what available sources, processors, or sinks can be used.
23. White space and quote rules
It is only necessary to quote parameter values if they contain spaces or the |
character. Here the transform processor is being passed a SpEL expression that will be applied to any data it encounters:
transform --expression='new StringBuilder(payload).reverse()'
If the parameter value needs to embed a single quote, use two single quotes:
// Query is: Select * from /Customers where name='Smith' scan --query='Select * from /Customers where name=''Smith'''
23.1. Quotes and Escaping
There is a Spring Shell based client that talks to the Data Flow Server that is responsible for parsing the DSL. In turn, applications may have applications properties that rely on embedded languages, such as the Spring Expression Language.
The shell, Data Flow DSL parser, and SpEL have rules about how they handle quotes and how syntax escaping works. When combined together, confusion may arise. This section explains the rules that apply and provides examples of the most complicated situations you will encounter when all three components are involved.
It’s not always that complicated
If you don’t use the Data Flow shell, for example you’re using the REST API directly, or if applications properties are not SpEL expressions, then escaping rules are simpler. |
23.1.1. Shell rules
Arguably, the most complex component when it comes to quotes is the shell. The rules can be laid out quite simply, though:
-
a shell command is made of keys (
--foo
) and corresponding values. There is a special, key-less mapping though, see below -
a value can not normally contain spaces, as space is the default delimiter for commands
-
spaces can be added though, by surrounding the value with quotes (either single [
'
] or double ["
] quotes) -
if surrounded with quotes, a value can embed a literal quote of the same kind by prefixing it with a backslash (
\
) -
Other escapes are available, such as
\t
,\n
,\r
,\f
and unicode escapes of the form\uxxxx
-
Lastly, the key-less mapping is handled in a special way in the sense that if does not need quoting to contain spaces
For example, the shell supports the !
command to execute native shell commands. The !
accepts a single, key-less argument. This is why the following works:
dataflow:>! rm foo
The argument here is the whole rm foo
string, which is passed as is to the underlying shell.
As another example, the following commands are strictly equivalent, and the argument value is foo
(without the quotes):
dataflow:>stream destroy foo dataflow:>stream destroy --name foo dataflow:>stream destroy "foo" dataflow:>stream destroy --name "foo"
23.1.2. DSL parsing rules
At the parser level (that is, inside the body of a stream or task definition) the rules are the following:
-
option values are normally parsed until the first space character
-
they can be made of literal strings though, surrounded by single or double quotes
-
To embed such a quote, use two consecutive quotes of the desired kind
As such, the values of the --expression
option to the filter application are semantically equivalent in the following examples:
filter --expression=payload>5 filter --expression="payload>5" filter --expression='payload>5' filter --expression='payload > 5'
Arguably, the last one is more readable. It is made possible thanks to the surrounding quotes. The actual expression is payload > 5
(without quotes).
Now, let’s imagine we want to test against string messages. If we’d like to compare the payload to the SpEL literal string, "foo"
, this is how we could do:
filter --expression=payload=='foo' (1) filter --expression='payload == ''foo''' (2) filter --expression='payload == "foo"' (3)
1 | This works because there are no spaces. Not very legible though |
2 | This uses single quotes to protect the whole argument, hence actual single quotes need to be doubled |
3 | But SpEL recognizes String literals with either single or double quotes, so this last method is arguably the best |
Please note that the examples above are to be considered outside of the shell, for example if when calling the REST API directly. When entered inside the shell, chances are that the whole stream definition will itself be inside double quotes, which would need escaping. The whole example then becomes:
dataflow:>stream create foo --definition "http | filter --expression=payload='foo' | log" dataflow:>stream create foo --definition "http | filter --expression='payload == ''foo''' | log" dataflow:>stream create foo --definition "http | filter --expression='payload == \"foo\"' | log"
23.1.3. SpEL syntax and SpEL literals
The last piece of the puzzle is about SpEL expressions. Many applications accept options that are to be interpreted as SpEL expressions, and as seen above, String literals are handled in a special way there too. The rules are:
-
literals can be enclosed in either single or double quotes
-
quotes need to be doubled to embed a literal quote. Single quotes inside double quotes need no special treatment, and vice versa
As a last example, assume you want to use the transform processor.
This processor accepts an expression
option which is a SpEL expression. It is to be evaluated against the incoming message, with a default of payload
(which forwards the message payload untouched).
It is important to understand that the following are equivalent:
transform --expression=payload transform --expression='payload'
but very different from the following:
transform --expression="'payload'" transform --expression='''payload'''
and other variations.
The first series will simply evaluate to the message payload, while the latter examples will evaluate to the actual literal string payload
(again, without quotes).
23.1.4. Putting it all together
As a last, complete example, let’s review how one could force the transformation of all messages to the string literal hello world
, by creating a stream in the context of the Data Flow shell:
dataflow:>stream create foo --definition "http | transform --expression='''hello world''' | log" (1) dataflow:>stream create foo --definition "http | transform --expression='\"hello world\"' | log" (2) dataflow:>stream create foo --definition "http | transform --expression=\"'hello world'\" | log" (2)
1 | This uses single quotes around the string (at the Data Flow parser level), but they need to be doubled because we’re inside a string literal (very first single quote after the equals sign) |
2 | use single and double quotes respectively to encompass the whole string at the Data Flow parser level. Hence, the other kind of quote can be used inside the string. The whole thing is inside the --definition argument to the shell though, which uses double quotes. So double quotes are escaped (at the shell level)
|
Streams
This section goes into more detail about how you can create Streams which are a collection of Spring Cloud Stream. It covers topics such as creating and deploying Streams.
If you’re just starting out with Spring Cloud Data Flow, you should probably read the Getting Started guide before diving into this section.
24. Introduction
Streams are a collection of long lived Spring Cloud Stream applications that communicate with each other over messaging middleware. A text based DSL defines the configuration and data flow between the applications. While many applications are provided for you to implement common use-cases, you will typically create a custom Spring Cloud Stream application to implement custom business logic.
The general lifecycle of a Stream is:
-
Register applications
-
Create a Stream Definition
-
Deploy the Stream
-
Undeploy or Destroy the Stream.
There are two options for deploying streams:
-
Use a Data Flow Server implementation that deploys to a single platform.
-
Configure the Data Flow Server to delegate the deployment to new server in the Spring Cloud ecosystem named Skipper.
When using the first option, you can use the Data Flow Server for Cloud Foundry to deploy streams to a single org and space on Cloud Foundry. Alternatively, you can use Data Flow for Kuberenetes to deploy stream to a single namespace on a Kubernetes cluster. See here for a list of implementations.
When using the second option, you can configure Skipper to deploy applications to one or more Cloud Foundry org/spaces, one or more namespaces on a Kubernetes cluster, as well as deploy to the local machine. When deploying a stream in Data Flow using Skipper, you can specify which platfrom to use. Skipper also provides Data Flow with the ability to perform updates to deployed streams. There are many ways the applications in a stream can be updated, but one of the most common examples is to upgrade a processor application with new custom business logic while leaving the existing source and sink applications alone.
24.1. Stream Pipeline DSL
A stream is defined using a unix-inspired Pipeline syntax.
The syntax uses vertical bars, also known as "pipes" to connect multiple commands.
The command ls -l | grep key | less
in Unix takes the output of the ls -l
process and pipes it to the input of the grep key
process.
The output of grep
in turn is sent to the input of the less
process.
Each |
symbol will connect the standard ouput of the program on the left to the standard input of the command on the right.
Data flows through the pipeline from left to right.
In Data Flow, the Unix command is replaced by a Spring Cloud Stream application and each pipe symbol represents connecting the input and output of applications via messaging middleware, such as RabbitMQ or Apache Kafka.
Each Spring Cloud Stream application is registered under a simple name. The registration process specifies where the application can be obtained, for example in a Maven Repository or a Docker registry. You can find out more information on how to register Spring Cloud Stream applications in this section. In Data Flow, we classify the Spring Cloud Stream applications as either Sources, Processors, or Sinks.
As a simple example consider the collection of data from an HTTP Source writing to a File Sink. Using the DSL the stream description is:
http | file
A stream that involves some processing would be expresed as:
http | filter | transform | file
Stream definitions can be created using the shell’s create stream
command. For example:
dataflow:> stream create --name httpIngest --definition "http | file"
The Stream DSL is passed in to the --definition
command option.
The deployment of stream definitions is done via the shell’s stream deploy
command.
dataflow:> stream deploy --name ticktock
The Getting Started section shows you how to start the server and how to start and use the Spring Cloud Data Flow shell.
Note that shell is calling the Data Flow Servers' REST API. For more information on making HTTP request directly to the server, consult the REST API Guide.
24.2. Application properties
Each application takes properties to customize its behavior. As an example the http
source module exposes a port
setting which allows the data ingestion port to be changed from the default value.
dataflow:> stream create --definition "http --port=8090 | log" --name myhttpstream
This port
property is actually the same as the standard Spring Boot server.port
property.
Data Flow adds the ability to use the shorthand form port
instead of server.port
.
One may also specify the longhand version as well.
dataflow:> stream create --definition "http --server.port=8000 | log" --name myhttpstream
This shorthand behavior is discussed more in the section on Whitelisting application properties.
If you have registered application property metadata you can use tab completion in the shell after typing --
to get a list of candidate property names.
The shell provides tab completion for application properties and also the shell command app info <appType>:<appName>
provides additional documentation for all the supported properties.
Supported Stream `<appType>’s are: source, processor, and sink |
25. Stream Lifecycle
25.1. Register a Stream App
Register a Stream App with the App Registry using the Spring Cloud Data Flow Shell
app register
command. You must provide a unique name, application type, and a URI that can be
resolved to the app artifact. For the type, specify "source", "processor", or "sink".
Here are a few examples:
dataflow:>app register --name mysource --type source --uri maven://com.example:mysource:0.0.1-SNAPSHOT
dataflow:>app register --name myprocessor --type processor --uri file:///Users/example/myprocessor-1.2.3.jar
dataflow:>app register --name mysink --type sink --uri http://example.com/mysink-2.0.1.jar
When providing a URI with the maven
scheme, the format should conform to the following:
maven://<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
For example, if you would like to register the snapshot versions of the http
and log
applications built with the RabbitMQ binder, you could do the following:
dataflow:>app register --name http --type source --uri maven://org.springframework.cloud.stream.app:http-source-rabbit:1.2.1.BUILD-SNAPSHOT
dataflow:>app register --name log --type sink --uri maven://org.springframework.cloud.stream.app:log-sink-rabbit:1.2.1.BUILD-SNAPSHOT
If you would like to register multiple apps at one time, you can store them in a properties file
where the keys are formatted as <type>.<name>
and the values are the URIs.
For example, if you would like to register the snapshot versions of the http
and log
applications built with the RabbitMQ binder, you could have the following in a properties file [eg: stream-apps.properties]:
source.http=maven://org.springframework.cloud.stream.app:http-source-rabbit:1.2.1.BUILD-SNAPSHOT
sink.log=maven://org.springframework.cloud.stream.app:log-sink-rabbit:1.2.1.BUILD-SNAPSHOT
Then to import the apps in bulk, use the app import
command and provide the location of the properties file via --uri
:
dataflow:>app import --uri file:///<YOUR_FILE_LOCATION>/stream-apps.properties
25.2. Register Supported Applications and Tasks
For convenience, we have the static files with application-URIs (for both maven and docker) available for all the out-of-the-box stream and task/batch app-starters. You can point to this file and import all the application-URIs in bulk. Otherwise, as explained in previous paragraphs, you can register them individually or have your own custom property file with only the required application-URIs in it. It is recommended, however, to have a "focused" list of desired application-URIs in a custom property file.
List of available Stream Application Starters:
Artifact Type | Stable Release | SNAPSHOT Release |
---|---|---|
RabbitMQ + Maven |
bit.ly/Celsius-BUILD-SNAPSHOT-stream-applications-rabbit-maven |
|
RabbitMQ + Docker |
bit.ly/Celsius-BUILD-SNAPSHOT-stream-applications-rabbit-docker |
|
Kafka 0.10 + Maven |
bit.ly/Celsius-BUILD-SNAPSHOT-stream-applications-kafka-10-maven |
|
Kafka 0.10 + Docker |
bit.ly/Celsius-BUILD-SNAPSHOT-stream-applications-kafka-10-docker |
List of available Task Application Starters:
Artifact Type | Stable Release | SNAPSHOT Release |
---|---|---|
Maven |
||
Docker |
You can find more information about the available task starters in the Task App Starters Project Page and related reference documentation. For more information about the available stream starters look at the Stream App Starters Project Page and related reference documentation.
As an example, ff you would like to register all out-of-the-box stream applications built with the Kafka binder in bulk, you can with the following command.
$ dataflow:>app import --uri http://bit.ly/Celsius-SR1-stream-applications-kafka-10-maven
Alternatively you can register all the stream applications with the Rabbit binder
$ dataflow:>app import --uri http://bit.ly/Celsius-SR1-stream-applications-rabbit-maven
You can also pass the --local
option (which is true
by default) to indicate whether the
properties file location should be resolved within the shell process itself. If the location should
be resolved from the Data Flow Server process, specify --local false
.
When using either Note however that once downloaded, applications may be cached locally on the Data Flow server, based on the resource
location. If the resource location doesn’t change (even though the actual resource bytes may be different), then it
won’t be re-downloaded. When using Moreover, if a stream is already deployed and using some version of a registered app, then (forcibly) re-registering a different app will have no effect until the stream is deployed anew. |
In some cases the Resource is resolved on the server side, whereas in others the URI will be passed to a runtime container instance where it is resolved. Consult the specific documentation of each Data Flow Server for more detail. |
25.2.1. Whitelisting application properties
Stream and Task applications are Spring Boot applications which are aware of many Common application properties, e.g. server.port
but also families of properties such as those with the prefix spring.jmx
and logging
. When creating your own application it is desirable to whitelist properties so that the shell and the UI can display them first as primary properties when presenting options via TAB completion or in drop-down boxes.
To whitelist application properties create a file named spring-configuration-metadata-whitelist.properties
in the META-INF
resource directory. There are two property keys that can be used inside this file. The first key is named configuration-properties.classes
. The value is a comma separated list of fully qualified @ConfigurationProperty
class names. The second key is configuration-properties.names
whose value is a comma separated list of property names. This can contain the full name of property, such as server.port
or a partial name to whitelist a category of property names, e.g. spring.jmx
.
The Spring Cloud Stream application starters are a good place to look for examples of usage. Here is a simple example of the file sink’s spring-configuration-metadata-whitelist.properties
file
configuration-properties.classes=org.springframework.cloud.stream.app.file.sink.FileSinkProperties
If we also wanted to add server.port
to be white listed, then it would look like this:
configuration-properties.classes=org.springframework.cloud.stream.app.file.sink.FileSinkProperties
configuration-properties.names=server.port
Make sure to add 'spring-boot-configuration-processor' as an optional dependency to generate configuration metadata file for the properties.
|
25.2.2. Creating and using a dedicated metadata artifact
You can go a step further in the process of describing the main properties that your stream or task app supports by creating a so-called metadata companion artifact. This simple jar file contains only the Spring boot JSON file about configuration properties metadata, as well as the whitelisting file described in the previous section.
Here is the contents of such an artifact, for the canonical log
sink:
$ jar tvf log-sink-rabbit-1.2.1.BUILD-SNAPSHOT-metadata.jar
373848 META-INF/spring-configuration-metadata.json
174 META-INF/spring-configuration-metadata-whitelist.properties
Note that the spring-configuration-metadata.json
file is quite large. This is because it contains the concatenation of all the properties that
are available at runtime to the log
sink (some of them come from spring-boot-actuator.jar
, some of them come from
spring-boot-autoconfigure.jar
, even some more from spring-cloud-starter-stream-sink-log.jar
, etc.) Data Flow
always relies on all those properties, even when a companion artifact is not available, but here all have been merged
into a single file.
To help with that (as a matter of fact, you don’t want to try to craft this giant JSON file by hand), you can use the following plugin in your build:
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-app-starter-metadata-maven-plugin</artifactId>
<executions>
<execution>
<id>aggregate-metadata</id>
<phase>compile</phase>
<goals>
<goal>aggregate-metadata</goal>
</goals>
</execution>
</executions>
</plugin>
This plugin comes in addition to the spring-boot-configuration-processor that creates the individual JSON files.
Be sure to configure the two!
|
The benefits of a companion artifact are manifold:
-
being way lighter (usually a few kilobytes, as opposed to megabytes for the actual app), they are quicker to download, allowing quicker feedback when using e.g.
app info
or the Dashboard UI -
as a consequence of the above, they can be used in resource constrained environments (such as PaaS) when metadata is the only piece of information needed
-
finally, for environments that don’t deal with boot uberjars directly (for example, Docker-based runtimes such as Kubernetes or Mesos), this is the only way to provide metadata about the properties supported by the app.
Remember though, that this is entirely optional when dealing with uberjars. The uberjar itself also includes the metadata in it already.
25.2.3. Using the companion artifact
Once you have a companion artifact at hand, you need to make the system aware of it so that it can be used.
When registering a single app via app register
, you can use the optional --metadata-uri
option in the shell, like so:
dataflow:>app register --name log --type sink
--uri maven://org.springframework.cloud.stream.app:log-sink-kafka-10:1.2.1.BUILD-SNAPSHOT
--metadata-uri=maven://org.springframework.cloud.stream.app:log-sink-kafka-10:jar:metadata:1.2.1.BUILD-SNAPSHOT
When registering several files using the app import
command, the file should contain a <type>.<name>.metadata
line
in addition to each <type>.<name>
line. This is optional (i.e. if some apps have it but some others don’t, that’s fine).
Here is an example for a Dockerized app, where the metadata artifact is being hosted in a Maven repository (but retrieving
it via http://
or file://
would be equally possible).
...
source.http=docker:springcloudstream/http-source-rabbit:latest
source.http.metadata=maven://org.springframework.cloud.stream.app:http-source-rabbit:jar:metadata:1.2.1.BUILD-SNAPSHOT
...
25.3. Creating custom applications
While there are out of the box source, processor, sink applications available, one can extend these applications or write a custom Spring Cloud Stream application.
The process of creating Spring Cloud Stream applications via Spring Initializr is detailed in the Spring Cloud Stream {spring-cloud-stream-docs}#_getting_started[documentation]. It is possible to include multiple binders to an application. If doing so, refer the instructions in Passing Spring Cloud Stream properties on how to configure them.
For supporting property whitelisting, Spring Cloud Stream applications running in Spring Cloud Data Flow may include the Spring Boot configuration-processor
as an optional dependency, as in the following example.
<dependencies>
<!-- other dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
Make sure that the |
Once a custom application has been created, it can be registered as described in Register a Stream App.
25.4. Creating a Stream
The Spring Cloud Data Flow Server exposes a full RESTful API for managing the lifecycle of stream definitions, but the easiest way to use is it is via the Spring Cloud Data Flow shell. Start the shell as described in the Getting Started section.
New streams are created by with the help of stream definitions. The definitions are built from a simple DSL. For example, let’s walk through what happens if we execute the following shell command:
dataflow:> stream create --definition "time | log" --name ticktock
This defines a stream named ticktock
based off the DSL expression time | log
. The DSL uses the "pipe" symbol |
, to connect a source to a sink.
25.4.1. Application properties
Application properties are the properties associated with each application in the stream. When the application is deployed, the application properties are applied to the application via command line arguments or environment variables based on the underlying deployment implementation.
The following stream
dataflow:> stream create --definition "time | log" --name ticktock
can have application properties defined at the time of stream creation.
The shell command app info <appType>:<appName>
displays the white-listed application properties for the application.
For more info on the property white listing refer to Whitelisting application properties
Below are the white listed properties for the app time
:
dataflow:> app info source:time
╔══════════════════════════════╤══════════════════════════════╤══════════════════════════════╤══════════════════════════════╗
║ Option Name │ Description │ Default │ Type ║
╠══════════════════════════════╪══════════════════════════════╪══════════════════════════════╪══════════════════════════════╣
║trigger.time-unit │The TimeUnit to apply to delay│<none> │java.util.concurrent.TimeUnit ║
║ │values. │ │ ║
║trigger.fixed-delay │Fixed delay for periodic │1 │java.lang.Integer ║
║ │triggers. │ │ ║
║trigger.cron │Cron expression value for the │<none> │java.lang.String ║
║ │Cron Trigger. │ │ ║
║trigger.initial-delay │Initial delay for periodic │0 │java.lang.Integer ║
║ │triggers. │ │ ║
║trigger.max-messages │Maximum messages per poll, -1 │1 │java.lang.Long ║
║ │means infinity. │ │ ║
║trigger.date-format │Format for the date value. │<none> │java.lang.String ║
╚══════════════════════════════╧══════════════════════════════╧══════════════════════════════╧══════════════════════════════╝
Below are the white listed properties for the app log
:
dataflow:> app info sink:log
╔══════════════════════════════╤══════════════════════════════╤══════════════════════════════╤══════════════════════════════╗
║ Option Name │ Description │ Default │ Type ║
╠══════════════════════════════╪══════════════════════════════╪══════════════════════════════╪══════════════════════════════╣
║log.name │The name of the logger to use.│<none> │java.lang.String ║
║log.level │The level at which to log │<none> │org.springframework.integratio║
║ │messages. │ │n.handler.LoggingHandler$Level║
║log.expression │A SpEL expression (against the│payload │java.lang.String ║
║ │incoming message) to evaluate │ │ ║
║ │as the logged message. │ │ ║
╚══════════════════════════════╧══════════════════════════════╧══════════════════════════════╧══════════════════════════════╝
The application properties for the time
and log
apps can be specified at the time of stream
creation as follows:
dataflow:> stream create --definition "time --fixed-delay=5 | log --level=WARN" --name ticktock
Note that the properties fixed-delay
and level
defined above for the apps time
and log
are the 'short-form' property names provided by the shell completion.
These 'short-form' property names are applicable only for the white-listed properties and in all other cases, only fully qualified property names should be used.
25.4.2. Common application properties
In addition to configuration via DSL, Spring Cloud Data Flow provides a mechanism for setting common properties to all
the streaming applications that are launched by it.
This can be done by adding properties prefixed with spring.cloud.dataflow.applicationProperties.stream
when starting
the server.
When doing so, the server will pass all the properties, without the prefix, to the instances it launches.
For example, all the launched applications can be configured to use a specific Kafka broker by launching the Data Flow server with the following options:
--spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.brokers=192.168.1.100:9092
--spring.cloud.dataflow.applicationProperties.stream.spring.cloud.stream.kafka.binder.zkNodes=192.168.1.100:2181
This will cause the properties spring.cloud.stream.kafka.binder.brokers
and spring.cloud.stream.kafka.binder.zkNodes
to be passed to all the launched applications.
Properties configured using this mechanism have lower precedence than stream deployment properties.
They will be overridden if a property with the same key is specified at stream deployment time (e.g.
app.http.spring.cloud.stream.kafka.binder.brokers will override the common property).
|
25.5. Deploying a Stream
This section describes how to deploy a Stream when the Spring Cloud Data Flow server is responsible for deploying the stream. The following section, Stream Lifecycle with Skipper, covers the new deployment and upgrade features when the Spring Cloud Data Flow server delegates to Skipper for stream deployment. In both cases, the description of how deployment properties applies to both approaches of Stream deployment.
Give the ticktock
stream definition:
dataflow:> stream create --definition "time | log" --name ticktock
You can deploy the stream using the following command: Then to deploy the stream execute the following shell command
dataflow:> stream deploy --name ticktock
The Data Flow Server resolves time
and log
to maven coordinates and uses those to launch the time
and log
applications of the stream.
2016-06-01 09:41:21.728 INFO 79016 --- [nio-9393-exec-6] o.s.c.d.spi.local.LocalAppDeployer : deploying app ticktock.log instance 0
Logs will be in /var/folders/wn/8jxm_tbd1vj28c8vj37n900m0000gn/T/spring-cloud-dataflow-912434582726479179/ticktock-1464788481708/ticktock.log
2016-06-01 09:41:21.914 INFO 79016 --- [nio-9393-exec-6] o.s.c.d.spi.local.LocalAppDeployer : deploying app ticktock.time instance 0
Logs will be in /var/folders/wn/8jxm_tbd1vj28c8vj37n900m0000gn/T/spring-cloud-dataflow-912434582726479179/ticktock-1464788481910/ticktock.time
In this example, the time source simply sends the current time as a message each second, and the log sink outputs it using the logging framework.
You can tail the stdout
log (which has an "_<instance>" suffix). The log files are located within the directory displayed in the Data Flow Server’s log output, as shown above.
$ tail -f /var/folders/wn/8jxm_tbd1vj28c8vj37n900m0000gn/T/spring-cloud-dataflow-912434582726479179/ticktock-1464788481708/ticktock.log/stdout_0.log
2016-06-01 09:45:11.250 INFO 79194 --- [ kafka-binder-] log.sink : 06/01/16 09:45:11
2016-06-01 09:45:12.250 INFO 79194 --- [ kafka-binder-] log.sink : 06/01/16 09:45:12
2016-06-01 09:45:13.251 INFO 79194 --- [ kafka-binder-] log.sink : 06/01/16 09:45:13
You can also create an deploy the stream in one step by passing the --deploy
flag when creating the stream.
dataflow:> stream create --definition "time | log" --name ticktock --deploy
However, it is not very common in real world use cases to do create and deploy the stream in one step.
The reason is that when you use the stream deploy
command, you can pass in properties that define how to map the applications onto the platform, e.g. what is the memory size of the container to use, the number of each application to run, or to enable data partitioning features.
Properties can also override application properties which were set when creating the stream.
The next sections cover this in detail.
25.5.1. Deployment properties
When deploying a stream, you can specify properties that fall into two groups.
-
Properties that control how the apps are deployed to the target platform. These properties use a
deployer
prefix. These are referred to asdeployer
properties. -
Properties that set application properties or override application properties set during stream creation. These are referred to as
application
properties.
The syntax for deployer
properties is deployer.<app-name>.<short-property-name>=<value>
and the syntax for application
properties app.<app-name>.<property-name>=<value>
. This syntax is used when passing deployment properties via the shell. You may also specify them in a YAML file which is discussed below.
The following table shows the difference in behavior between settings deployer
and application
properties when deploying an application.
Application Properties | Deployer Properties | |
---|---|---|
Example Syntax |
|
|
What the application "sees" |
|
Nothing |
What the deployer "sees" |
Nothing |
|
Typical usage |
Passing/Overriding application properties, passing Spring Cloud Stream binder or partitionning properties |
Setting the number of instances, memory, disk, etc. |
Passing instance count
If you would like to have multiple instances of an application in the stream, you can include a deployer property with the deploy command:
dataflow:> stream deploy --name ticktock --properties "deployer.time.count=3"
Note that count
is the reserved property name used by the underlying deployer. Hence, if the application also has a custom property named count
, it is not supported
when specified in 'short-form' form during stream deployment as it could conflict with the instance count deployer property. Instead, the count
as a custom application property can be
specified in its fully qualified form (example: app.foo.bar.count
) during stream deployment or it can be specified using 'short-form' or fully qualified form during the stream creation
where it will be considered as an app property.
Inline vs file based properties
When using the Spring Cloud Data Flow Shell, there are two ways to provide deployment properties: either inline or via a file reference. Those two ways are exclusive and documented below:
- Inline properties
-
use the
--properties
shell option and list properties as a comma separated list of key=value pairs, like so:
stream deploy foo
--properties "deployer.transform.count=2,app.transform.producer.partitionKeyExpression=payload"
- Using a file reference
-
use the
--propertiesFile
option and point it to a local.properties
,.yaml
or.yml
file (i.e. that lives in the filesystem of the machine running the shell). Being read as a.properties
file, normal rules apply (ISO 8859-1 encoding,=
,<space>
or:
delimiter, etc.) although we recommend using=
as a key-value pair delimiter for consistency:
stream deploy foo --propertiesFile myprops.properties
where myprops.properties
contains:
deployer.transform.count=2
app.transform.producer.partitionKeyExpression=payload
Both the above properties will be passed as deployment properties for the stream foo
above.
In case of using YAML as the format for the deployment properties, use the .yaml
or .yml
file extention when deploying the stream,
stream deploy foo --propertiesFile myprops.yaml
where myprops.yaml
contains:
deployer:
transform:
count: 2
app:
transform:
producer:
partitionKeyExpression: payload
Passing application properties
The application properties can also be specified when deploying a stream. When specified during deployment, these application properties can either be specified as 'short-form' property names (applicable for white-listed properties) or fully qualified property names. The application properties should have the prefix "app.<appName/label>".
For example, the stream
dataflow:> stream create --definition "time | log" --name ticktock
can be deployed with application properties using the 'short-form' property names:
dataflow:>stream deploy ticktock --properties "app.time.fixed-delay=5,app.log.level=ERROR"
When using the app label,
stream create ticktock --definition "a: time | b: log"
the application properties can be defined as:
stream deploy ticktock --properties "app.a.fixed-delay=4,app.b.level=ERROR"
Passing Spring Cloud Stream properties
Spring Cloud Data Flow sets the required
Spring Cloud Stream properties for the applications inside the stream. Most importantly, the spring.cloud.stream.bindings.<input/output>.destination
is set internally for the apps to bind.
If someone wants to override any of the Spring Cloud Stream properties, they can be set via deployment properties.
For example, for the below stream
dataflow:> stream create --definition "http | transform --expression=payload.getValue('hello').toUpperCase() | log" --name ticktock
if there are multiple binders available in the classpath for each of the applications and the binder is chosen for each deployment then the stream can be deployed with the specific Spring Cloud Stream properties as:
dataflow:>stream deploy ticktock --properties "app.time.spring.cloud.stream.bindings.output.binder=kafka,app.transform.spring.cloud.stream.bindings.input.binder=kafka,app.transform.spring.cloud.stream.bindings.output.binder=rabbit,app.log.spring.cloud.stream.bindings.input.binder=rabbit"
Overriding the destination names is not recommended as Spring Cloud Data Flow takes care of setting this internally. |
Passing per-binding producer consumer properties
A Spring Cloud Stream application can have producer and consumer properties set per-binding
basis.
While Spring Cloud Data Flow supports specifying short-hand notation for per binding producer properties such as partitionKeyExpression
, partitionKeyExtractorClass
as described in Passing stream partition properties, all the supported Spring Cloud Stream producer/consumer properties can be set as Spring Cloud Stream properties for the app directly as well.
The consumer properties can be set for the inbound
channel name with the prefix app.[app/label name].spring.cloud.stream.bindings.<channelName>.consumer.
and the producer properties can be set for the outbound
channel name with the prefix app.[app/label name].spring.cloud.stream.bindings.<channelName>.producer.
.
For example, the stream
dataflow:> stream create --definition "time | log" --name ticktock
can be deployed with producer/consumer properties as:
dataflow:>stream deploy ticktock --properties "app.time.spring.cloud.stream.bindings.output.producer.requiredGroups=myGroup,app.time.spring.cloud.stream.bindings.output.producer.headerMode=raw,app.log.spring.cloud.stream.bindings.input.consumer.concurrency=3,app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts=5"
The binder
specific producer/consumer properties can also be specified in a similar way.
For instance
dataflow:>stream deploy ticktock --properties "app.time.spring.cloud.stream.rabbit.bindings.output.producer.autoBindDlq=true,app.log.spring.cloud.stream.rabbit.bindings.input.consumer.transacted=true"
Passing stream partition properties
A common pattern in stream processing is to partition the data as it is streamed. This entails deploying multiple instances of a message consuming app and using content-based routing so that messages with a given key (as determined at runtime) are always routed to the same app instance. You can pass the partition properties during stream deployment to declaratively configure a partitioning strategy to route each message to a specific consumer instance.
See below for examples of deploying partitioned streams:
- app.[app/label name].producer.partitionKeyExtractorClass
-
The class name of a PartitionKeyExtractorStrategy (default
null
) - app.[app/label name].producer.partitionKeyExpression
-
A SpEL expression, evaluated against the message, to determine the partition key; only applies if
partitionKeyExtractorClass
is null. If both are null, the app is not partitioned (defaultnull
) - app.[app/label name].producer.partitionSelectorClass
-
The class name of a PartitionSelectorStrategy (default
null
) - app.[app/label name].producer.partitionSelectorExpression
-
A SpEL expression, evaluated against the partition key, to determine the partition index to which the message will be routed. The final partition index will be the return value (an integer) modulo
[nextModule].count
. If both the class and expression are null, the underlying binder’s default PartitionSelectorStrategy will be applied to the key (defaultnull
)
In summary, an app is partitioned if its count is > 1 and the previous app has a
partitionKeyExtractorClass
or partitionKeyExpression
(class takes precedence).
When a partition key is extracted, the partitioned app instance is determined by
invoking the partitionSelectorClass
, if present, or the partitionSelectorExpression % partitionCount
,
where partitionCount
is application count in the case of RabbitMQ, and the underlying
partition count of the topic in the case of Kafka.
If neither a partitionSelectorClass
nor a partitionSelectorExpression
is
present the result is key.hashCode() % partitionCount
.
Passing application content type properties
In a stream definition you can specify that the input or the output of an application need to be converted to a different type.
You can use the inputType
and outputType
properties to specify the content type for the incoming data and outgoing data, respectively.
For example, consider the following stream:
dataflow:>stream create tuple --definition "http | filter --inputType=application/x-spring-tuple
--expression=payload.hasFieldName('hello') | transform --expression=payload.getValue('hello').toUpperCase()
| log" --deploy
The http
app is expected to send the data in JSON and the filter
app receives the JSON data
and processes it as a Spring Tuple.
In order to do so, we use the inputType
property on the filter app to convert the data into the expected Spring Tuple format.
The transform
application processes the Tuple data and sends the processed data to the downstream log
application.
When sending some data to the http
application:
dataflow:>http post --data {"hello":"world","foo":"bar"} --contentType application/json --target http://localhost:<http-port>
At the log application you see the content as follows:
INFO 18745 --- [transform.tuple-1] log.sink : WORLD
Depending on how applications are chained, the content type conversion can be specified either as via the --outputType
in the upstream app or as an --inputType
in the downstream app.
For instance, in the above stream, instead of specifying the --inputType
on the 'transform' application to convert, the option --outputType=application/x-spring-tuple
can also be specified on the 'http' application.
For the complete list of message conversion and message converters, please refer to Spring Cloud Stream {spring-cloud-stream-docs}#contenttypemanagement[documentation].
Overriding application properties during stream deployment
Application properties that are defined during deployment override the same properties defined during the stream creation.
For example, the following stream has application properties defined during stream creation:
dataflow:> stream create --definition "time --fixed-delay=5 | log --level=WARN" --name ticktock
To override these application properties, one can specify the new property values during deployment:
dataflow:>stream deploy ticktock --properties "app.time.fixed-delay=4,app.log.level=ERROR"
25.6. Destroying a Stream
You can delete a stream by issuing the stream destroy
command from the shell:
dataflow:> stream destroy --name ticktock
If the stream was deployed, it will be undeployed before the stream definition is deleted.
25.7. Undeploying Streams
Often you will want to stop a stream, but retain the name and definition for future use. In that case you can undeploy
the stream by name.
dataflow:> stream undeploy --name ticktock
dataflow:> stream deploy --name ticktock
You can issue the deploy
command at a later time to restart it.
dataflow:> stream deploy --name ticktock
26. Stream Lifecycle with Skipper
Skipper is a server that allows you to discover Spring Boot applications and manage their lifecycle on multiple Cloud Platforms.
Applications in Skipper are bundled as packages which contain templated configuration files. They also contain an optional values
file that contains default values using to fill in template placeholders. You can find out more about the format of the package .zip file in Skipper’s documentation on Packages.
Skipper’s templated configuration files contain placeholders for application properties, application version, and deployment properties.
Package .zip files are uploaded to Skipper and stored in a package repository.
Skipper’s package repository is analogous to those found in tools such as apt-get
or brew
.
You can override template values when installing or upgrading a package. Skipper orchestrates the upgrade/rollback procedure of applications between different versions, taking the minimal set of actions to bring the system to the desired state. For example, if only one application in a stream has been updated, only that single application is deployed with a new version and the old version undeployed. An application is considered different when upgrading if any of it’s application properties, deployment properties (excluding count), or application version (e.g. 1.0.0.RELEASE) is different from the currently installed application.
Spring Cloud Data Flow is integrated with Skipper by generating a Skipper package when deploying a Stream. The generated package name is the same name as the Stream. The generated package is uploaded to Skipper’s package repository and Data Flow then instructs Skipper to install the package that corresponds to the Stream. Subsequent commands to upgrade and rollback the applications within the Stream are passed through to Skipper after some validation checks are performed by Data Flow.
26.1. Register a Versioned Stream App
Skipper extends the Register a Stream App lifecycle with support of multi-versioned stream applications. This allows to upgrade or rollback those applications at runtime using the deployment properties.
Register a versioned stream application using the app register
command. You must provide a unique name, application type, and a URI that can be resolved to the app artifact.
For the type, specify "source", "processor", or "sink". The version is resolved from the URI. Here are a few examples:
dataflow:>app register --name mysource --type source --uri maven://com.example:mysource:0.0.1
dataflow:>app register --name mysource --type source --uri maven://com.example:mysource:0.0.2
dataflow:>app register --name mysource --type source --uri maven://com.example:mysource:0.0.3
dataflow:>app list --id source:mysource
╔══════════════════╤═════════╤════╤════╗
║ source │processor│sink│task║
╠══════════════════╪═════════╪════╪════╣
║> mysource-0.0.1 <│ │ │ ║
║mysource-0.0.2 │ │ │ ║
║mysource-0.0.3 │ │ │ ║
╚══════════════════╧═════════╧════╧════╝
The application URI should conform to one the following schema formats:
-
maven schema
maven://<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
-
http schema
http://<web-path>/<artifactName>-<version>.jar
-
file schema
file:///<local-path>/<artifactName>-<version>.jar
-
docker schema
docker:<docker-image-path>/<imageName>:<version>
The URI <version> part is compulsory for the versioned stream applications
|
Multiple versions can be registered for the same applications (e.g. same name and type) but only one can be set as default. The default version is used for deploying Streams.
The first time an application is registered it will be marked as default. The default application version can be altered with the app default
command:
dataflow:>app default --id source:mysource --version 0.0.2
dataflow:>app list --id source:mysource
╔══════════════════╤═════════╤════╤════╗
║ source │processor│sink│task║
╠══════════════════╪═════════╪════╪════╣
║mysource-0.0.1 │ │ │ ║
║> mysource-0.0.2 <│ │ │ ║
║mysource-0.0.3 │ │ │ ║
╚══════════════════╧═════════╧════╧════╝
The app list --id <type:name>
command lists all versions for a given stream application.
The app unregister
command has an optional --version
parameter to specify the app version to unregister.
dataflow:>app unregister --name mysource --type source --version 0.0.1
dataflow:>app list --id source:mysource
╔══════════════════╤═════════╤════╤════╗
║ source │processor│sink│task║
╠══════════════════╪═════════╪════╪════╣
║> mysource-0.0.2 <│ │ │ ║
║mysource-0.0.3 │ │ │ ║
╚══════════════════╧═════════╧════╧════╝
If a --version
is not specified, the default version is unregistered.
All applications in a stream should have a default version set for the stream to be deployed.
Otherwise they will be treated as unregistered application during the deployment.
Use the |
app default --id source:mysource --version 0.0.3
dataflow:>app list --id source:mysource
╔══════════════════╤═════════╤════╤════╗
║ source │processor│sink│task║
╠══════════════════╪═════════╪════╪════╣
║mysource-0.0.2 │ │ │ ║
║> mysource-0.0.3 <│ │ │ ║
╚══════════════════╧═════════╧════╧════╝
The stream deploy
necessitates default app versions to be set.
The stream update
and stream rollback
commands though can use all (default and non-default) registered app versions.
dataflow:>stream create foo --definition "mysource | log"
This will create stream using the default mysource version (0.0.3). Then we can update the version to 0.0.2 like this:
dataflow:>stream update foo --properties version.mysource=0.0.2
Only pre-registered applications can be used to |
An attempt to update the mysource
to version 0.0.1
(not registered) will fail!
26.2. Creating and Deploying a Stream
You create and deploy a stream as follows:
dataflow:> stream create --name httptest --definition "http --server.port=9000 | log" --deploy
If you want to pass deployment properties, you can create and deploy a stream in two steps:
dataflow:> stream create --name httptest --definition "http --server.port=9000 | log"
dataflow:> stream deploy --name httptest
The command stream info
shows useful information about the stream including the deployment properties.
dataflow:>stream info httptest
╔══════════════════════════════╤══════════════════════════════╤══════════════════════════════╗
║ Name │ DSL │ Status ║
╠══════════════════════════════╪══════════════════════════════╪══════════════════════════════╣
║httptest │http --server.port=9000 | log │deploying ║
╚══════════════════════════════╧══════════════════════════════╧══════════════════════════════╝
Stream Deployment properties: {
"log" : {
"spring.cloud.deployer.indexed" : "true",
"spring.cloud.deployer.group" : "httptest",
"maven://org.springframework.cloud.stream.app:log-sink-rabbit" : "1.1.0.RELEASE"
},
"http" : {
"spring.cloud.deployer.group" : "httptest",
"maven://org.springframework.cloud.stream.app:http-source-rabbit" : "1.1.0.RELEASE"
}
}
There is an important optional command argument to the stream deploy
command, which is --platformName
.
Skipper can be configured to deploy to multiple platforms.
Skipper is pre-configured with a platform named default
which will deploys applications to the local machine where Skipper is running.
The default value of the command line argument --platformName
is default
.
If you are commonly deploying to one platform, when installing Skipper you can override the configuration of the default
platform.
Otherwise, specify the platformName to one of the values returned by the command stream platform-list
In future releases, only the local Data Flow server will be configured with the default platform.
|
26.3. Updating a Stream
To update the stream, use the command stream update
which takes as a command argument either --properties
or --propertiesFile
.
You can pass in values to these command arguments in the same format as when deploy the stream with or without Skipper.
There is an important new top level prefix available when using Skipper, which is version
.
If the Stream http | log
was deployed, and the version of log
which registered at the time of deployment was 1.1.0.RELEASE
, the following command will update the Stream to use the 1.2.0.RELEASE
of the log application.
Before updating the stream with the specific version of the app, we need to make sure that the app is registered with that version.
dataflow:>app register --name log --type sink --uri maven://org.springframework.cloud.stream.app:log-sink-rabbit:1.2.0.RELEASE
Successfully registered application 'sink:log'
dataflow:>stream update --name httptest --properties version.log=1.2.0.RELEASE
Only pre-registered application versions can be used to |
To verify the deployment properties and the updated version, we can use stream info
dataflow:>stream info httptest
╔══════════════════════════════╤══════════════════════════════╤══════════════════════════════╗
║ Name │ DSL │ Status ║
╠══════════════════════════════╪══════════════════════════════╪══════════════════════════════╣
║httptest │http --server.port=9000 | log │deploying ║
╚══════════════════════════════╧══════════════════════════════╧══════════════════════════════╝
Stream Deployment properties: {
"log" : {
"spring.cloud.deployer.indexed" : "true",
"spring.cloud.deployer.count" : "1",
"spring.cloud.deployer.group" : "httptest",
"maven://org.springframework.cloud.stream.app:log-sink-rabbit" : "1.2.0.RELEASE"
},
"http" : {
"spring.cloud.deployer.group" : "httptest",
"maven://org.springframework.cloud.stream.app:http-source-rabbit" : "1.1.0.RELEASE"
}
}
26.4. Stream versions
Skipper keeps a history of the Streams that were deployed.
After updating a Stream, there will be a second version of the stream.
You can query for the history of the versions using the command stream history --name <name-of-stream>
.
dataflow:>stream history --name httptest
╔═══════╤════════════════════════════╤════════╤════════════╤═══════════════╤════════════════╗
║Version│ Last updated │ Status │Package Name│Package Version│ Description ║
╠═══════╪════════════════════════════╪════════╪════════════╪═══════════════╪════════════════╣
║2 │Mon Nov 27 22:41:16 EST 2017│DEPLOYED│httptest │1.0.0 │Upgrade complete║
║1 │Mon Nov 27 22:40:41 EST 2017│DELETED │httptest │1.0.0 │Delete complete ║
╚═══════╧════════════════════════════╧════════╧════════════╧═══════════════╧════════════════╝
26.5. Stream Manifests
Skipper keeps an "manifest" of the all the applications, their application properties and deployment properties after all values have been substituted.
This represents the final state of what was deployed to the platform.
You can view the manifest for any of the versions of a Stream using the command stream manifest --name <name-of-stream> --releaseVersion <optional-version>
If the --releaseVersion
is not specified, the manifest for the last version is returned.
dataflow:>stream manifest --name httptest
---
# Source: log.yml
apiVersion: skipper.spring.io/v1
kind: SpringCloudDeployerApplication
metadata:
name: log
spec:
resource: maven://org.springframework.cloud.stream.app:log-sink-rabbit
version: 1.2.0.RELEASE
applicationProperties:
spring.metrics.export.triggers.application.includes: integration**
spring.cloud.dataflow.stream.app.label: log
spring.cloud.stream.metrics.key: httptest.log.${spring.cloud.application.guid}
spring.cloud.stream.bindings.input.group: httptest
spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.*
spring.cloud.dataflow.stream.name: httptest
spring.cloud.dataflow.stream.app.type: sink
spring.cloud.stream.bindings.input.destination: httptest.http
deploymentProperties:
spring.cloud.deployer.indexed: true
spring.cloud.deployer.group: httptest
spring.cloud.deployer.count: 1
---
# Source: http.yml
apiVersion: skipper.spring.io/v1
kind: SpringCloudDeployerApplication
metadata:
name: http
spec:
resource: maven://org.springframework.cloud.stream.app:http-source-rabbit
version: 1.2.0.RELEASE
applicationProperties:
spring.metrics.export.triggers.application.includes: integration**
spring.cloud.dataflow.stream.app.label: http
spring.cloud.stream.metrics.key: httptest.http.${spring.cloud.application.guid}
spring.cloud.stream.bindings.output.producer.requiredGroups: httptest
spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.*
server.port: 9000
spring.cloud.stream.bindings.output.destination: httptest.http
spring.cloud.dataflow.stream.name: httptest
spring.cloud.dataflow.stream.app.type: source
deploymentProperties:
spring.cloud.deployer.group: httptest
The majority of the deployment and application properties were set by Data Flow in order to enable the applications to talk to each other and sending application metrics with identifying labels.
26.6. Rollback a Stream
You can rollback to a previous version of the Stream using the command stream rollback
.
dataflow:>stream rollback --name httptest
There is an optional --releaseVersion
command argument which is the version of the Stream.
If not specified, the rollback goes to the previous stream version.
26.7. Application Count
The application count is a dynamic property of the system. If due to scaling at runtime, the application to be upgraded has 5 instances running, then 5 instances of the upgraded application will be deployed.
26.8. Skipper’s Upgrade Strategy
Skipper has a simple 'red/black' upgrade strategy. It deploys the new version of the applications, as many instances as the currently running version, and checks the /health
endpoint of the application.
If the health of the new application is good, then the previous application is undeployed.
If the health of the new application is bad, then all new applications are undeployed and the upgrade is considered not successful.
The upgrade strategy is not a rolling upgrade, so if 5 applications of the application to upgrade are runningn, then in a sunny day scenario, 5 of the new applications will also be running before the older version is undeployed. Future versions of Skipper will support rolling upgrades and other types of checks, e.g. manual, to continue to upgrade process.
27. Stream DSL
This section covers additional features of the Stream DSL not covered in the Stream DSL introduction.
27.1. Tap a Stream
Taps can be created at various producer endpoints in a stream. For a stream like this:
stream create --definition "http | step1: transform --expression=payload.toUpperCase() | step2: transform --expression=payload+'!' | log" --name mainstream --deploy
taps can be created at the output of http
, step1
and step2
.
To create a stream that acts as a 'tap' on another stream requires to specify the source destination name
for the tap stream. The syntax for source destination name is:
`:<streamName>.<label/appName>`
To create a tap at the output of http
in the stream above, the source destination name is mainstream.http
To create a tap at the output of the first transform app in the stream above, the source destination name is mainstream.step1
The tap stream DSL looks like this:
stream create --definition ":mainstream.http > counter" --name tap_at_http --deploy
stream create --definition ":mainstream.step1 > jdbc" --name tap_at_step1_transformer --deploy
Note the colon (:) prefix before the destination names. The colon allows the parser to recognize this as a destination name instead of an app name.
27.2. Using Labels in a Stream
When a stream is comprised of multiple apps with the same name, they must be qualified with labels:
stream create --definition "http | firstLabel: transform --expression=payload.toUpperCase() | secondLabel: transform --expression=payload+'!' | log" --name myStreamWithLabels --deploy
27.3. Named Destinations
Instead of referencing a source or sink applications, you can use a named destination.
A named destination corresponds to a specific destination name in the middleware broker (Rabbit, Kafka, etc.,).
When using the |
symbol, applications are connected to each other using messaging middleware destination names created by the Data Flow server.
In keeping with the unix analogy, one can redirect standard input and output using the less-than <
greater-than >
charaters.
To specify the name of the destination, prefix it with a colon :
.
For example the following stream has the destination name in the source
position:
dataflow:>stream create --definition ":myDestination > log" --name ingest_from_broker --deploy
This stream receives messages from the destination myDestination
located at the broker and connects it to the log
app. You can also create additional streams that will consume data from the same named destination.
The following stream has the destination name in the sink
position:
dataflow:>stream create --definition "http > :myDestination" --name ingest_to_broker --deploy
It is also possible to connect two different destinations (source
and sink
positions) at the broker in a stream.
dataflow:>stream create --definition ":destination1 > :destination2" --name bridge_destinations --deploy
In the above stream, both the destinations (destination1
and destination2
) are located in the broker. The messages flow from the source destination to the sink destination via a bridge
app that connects them.
27.4. Fan-in and Fan-out
Using named destinations, you can support Fan-in and Fan-out use cases. Fan-in use cases are when multiple sources all send data to the same named destination. For example
s3 > :data ftp > :data http > :data
Would direct the data payloads from the Amazon S3, FTP, and HTTP sources to the same named destination called data
. Then an additional stream created with the DSL expression
:data > file
would have all the data from those three sources sent to the file sink.
The Fan-out use case is when you determine the destination of a stream based on some information that is only known at runtime. In this case, the Router Application can be used to specify how to direct the incoming message to one of N named destinations.
28. Stream Java DSL
Instead of using the shell to create and deploy streams, you can use the Java based DSL provided by the spring-cloud-dataflow-rest-client
module.
The Java DSL is a convenient wrapper around the DataFlowTemplate
class that makes it simple to create and deploy streams programmatically.
To get started, you will need to add the following dependency to your project.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dataflow-rest-client</artifactId>
<version>1.3.0.RC1</version>
</dependency>
You will also need to add a reference to the Spring Milestone Maven repository.
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
A complete sample can be found in the Spring Cloud Data Flow Samples Repository to simplify getting started. |
28.1. Overview
The classes you will encounter using the Java DSL are StreamBuilder
, StreamDefinition
, Stream
, StreamApplication
, and DataFlowTemplate
.
The entry point is a builder
method on Stream
that takes an instance of a DataFlowTemplate
.
To create an instance of a DataFlowTemplate
you need to provide a URI
location of the Data Flow Server.
The DataFlowTemplate does not support a simple way to configure HTTP basic authentication or OAuth. This will be addressed in a future release.
|
We will now walk though a quick example, using the definition
style.
URI dataFlowUri = URI.create("http://localhost:9393");
DataFlowOperations dataFlowOperations = new DataFlowTemplate(dataFlowUri);
dataFlowOperations.appRegistryOperations().importFromResource(
"http://bit.ly/Celsius-RC1-stream-applications-rabbit-maven", true);
StreamDefinition streamDefinition = Stream.builder(dataFlowOperations)
.name("ticktock")
.definition("time | log")
.create();
The method create
returns an instance of a StreamDefinition
representing a Stream that has been created but not deployed.
This is called the definition
style since it takes as a single string for the stream definition, just like in the shell.
If applications have not yet been registered in the Data Flow server, you can use the DataFlowOperations
class to register them.
With the StreamDefinition
instance, you have methods available to deploy
or destory
the stream.
Stream stream = streamDefinition.deploy();
The Stream
instance has the methods getStatus
, destroy
and undeploy
to control and query the stream.
If you are going to immediately deploy the stream, there is no need to create a separate local variable of the type StreamDefinition
. You can just chain the calls together.
Stream stream = Stream.builder(dataFlowOperations)
.name("ticktock")
.definition("time | log")
.create()
.deploy();
The deploy
method is overloaded to take a java.util.Map
of deployment properties.
The StreamApplication
class is used in the 'fluent' Java DSL style and is discussed in the next section. The StreamBuilder
class is what is returned from the method Stream.builder(dataFlowOperations)
. In larger applications, it is common to create a single instance of the StreamBuilder
as a Spring @Bean
and share it across the application.
28.2. Java DSL styles
The Java DSL offers two styles to create Streams.
-
The
definition
style keeps the feel of using the pipes and filters textual DSL in the shell. This style is selected by using thedefinition
method after setting the stream name, e.g.Stream.builder(dataFlowOperations).name("ticktock").definition(<definition goes here>)
. -
The
fluent
style lets you chain together sources, processors and sinks by passing in an instance of aStreamApplication
. This style is selected by using thesource
method after setting the stream name, e.g.Stream.builder(dataFlowOperations).name("ticktock").source(<stream application instance goes here>)
. You then chain togetherprocessor()
andsink()
methods to create a stream definition.
To demonstrate both styles we will create a simple stream using both approaches. A complete sample for you to get started can be found in the Spring Cloud Data Flow Samples Repository
public void definitionStyle() throws Exception{
DataFlowOperations dataFlowOperations = createDataFlowOperations();
Map<String, String> deploymentProperties = createDeploymentProperties();
Stream woodchuck = Stream.builder(dataFlowOperations)
.name("woodchuck")
.definition("http --server.port=9900 | splitter --expression=payload.split(' ') | log")
.create()
.deploy(deploymentProperties);
waitAndDestroy(woodchuck)
}
public void fluentStyle() throws Exception {
DataFlowOperations dataFlowOperations = createDataFlowOperations();
StreamApplication source = new StreamApplication("http").addProperty("server.port", 9900);
StreamApplication processor = new StreamApplication("splitter")
.addProperty("producer.partitionKeyExpression", "payload");
StreamApplication sink = new StreamApplication("log")
.addDeploymentProperty("count", 2);
Stream woodchuck = Stream.builder(dataFlowOperations).name("woodchuck")
.source(source)
.processor(processor)
.sink(sink)
.create()
.deploy(deploymentProperties);
waitAndDestroy(woodchuck)
}
The waitAndDestroy
method uses the getStatus
method to poll for the stream’s status.
private void waitAndDestroy(Stream stream) throws InterruptedException {
while(!stream.getStatus().equals("deployed")){
System.out.println("Wating for deployment of stream.");
Thread.sleep(5000);
}
System.out.println("Letting the stream run for 2 minutes.");
// Let the stream run for 2 minutes
Thread.sleep(120000);
System.out.println("Destroying stream");
stream.destroy();
}
When using the definition style, the deployment properties are specified as a java.util.Map
in the same manner as using the shell. The method createDeploymentProperties
is defined as:
private Map<String, String> createDeploymentProperties() {
Map<String, String> deploymentProperties = new HashMap<>();
deploymentProperties.put("app.splitter.producer.partitionKeyExpression", "payload");
deploymentProperties.put("deployer.log.memory","512");
deploymentProperties.put("deployer.log.count", "2");
return deploymentProperties;
}
Is this case, application properties are also overridden at deployment time in addition to setting the deployer property count
for the log application.
When using the fluent style, the the deployment properties are added using the method addDeploymentProperty
, e.g. new StreamApplication("log").addDeploymentProperty("count", 2)
and you do not need to prefix the property with deployer.<app_name>
.
In order to create/deploy your streams, you need to make sure that the corresponding apps have been registered in the DataFlow server first.
Attempting to create or deploy a stream that contains an unknown app will throw an exception. You can register application using the DataFlowTemplate , e.g.
|
dataFlowOperations.appRegistryOperations().importFromResource(
"http://bit.ly/Celsius-RC1-stream-applications-rabbit-maven", true);
The Stream applications can also be beans within your application that are injected in other classes to create Streams.
There are many ways to structure Spring applications, but one way to structure it is to have an @Configuration
class define the StreamBuilder
and StreamApplications
.
@Configuration
public StreamConfiguration {
@Bean
public StreamBuilder builder() {
return Stream.builder(new DataFlowTemplate(URI.create("http://localhost:9393")));
}
@Bean
public StreamApplication httpSource(){
return new StreamApplication("http");
}
@Bean
public StreamApplication logSink(){
return new StreamApplication("log");
}
}
Then in another class you can @Autowire
these classes and deploy a stream.
@Component
public MyStreamApps {
@Autowired
private StreamBuilder streamBuilder;
@Autowired
private StreamApplication httpSource;
@Autowired
private StreamApplication logSink;
public void deploySimpleStream() {
Stream simpleStream = streamBuilder.name("simpleStream")
.source(httpSource);
.sink(logSink)
.create()
.deploy();
}
}
This style allows you to easily share StreamApplications
across multiple Streams.
28.3. Using the DeploymentPropertiesBuilder
Regardless of style you choose, the deploy(Map<String, String> deploymentProperties)
method allows customization of how your streams will be deployed. We made it a easier to create a map with properties by using a builder style, as well as creating static methods for some properties so you don’t need to remember the name of such properties. If you take the previous example of createDeploymentProperties
it could be rewritten as:
private Map<String, String> createDeploymentProperties() {
return new DeploymentPropertiesBuilder()
.count("log", 2)
.memory("log", 512)
.put("app.splitter.producer.partitionKeyExpression", "payload")
.build();
}
This utility class is meant to help with the creation of a Map and adds a few methods to assist with defining pre-defined properties.
29. Deploying using Skipper
If you desire to deploy your streams using Skipper, you need to pass certain properties to the server. With the new SkipperDeploymentPropertiesBuilder
we made it simpler for you to enable it.
private Map<String, String> createDeploymentProperties() {
return new SkipperDeploymentPropertiesBuilder()
.count("log", 2)
.memory("log", 512)
.put("app.splitter.producer.partitionKeyExpression", "payload")
.platformName("pcf")
.build();
}
30. Stream applications with multiple binder configurations
In some cases, a stream can have its applications bound to multiple spring cloud stream binders when they are required to connect to different messaging middleware configurations. In those cases, it is important to make sure the applications are configured appropriately with their binder configurations. For example, let’s consider the following stream:
http | transform --expression=payload.toUpperCase() | log
and in this stream, each application connects to messaging middleware in the following way:
Http source sends events to RabbitMQ (rabbit1)
Transform processor receives events from RabbitMQ (rabbit1) and sends the processed events into Kafka (kafka1)
Log sink receives events from Kafka (kafka1)
Here, rabbit1
and kafka1
are the binder names given in the spring cloud stream application properties.
Based on this setup, the applications will have the following binder(s) in their classpath with the appropriate configuration:
Http - Rabbit binder
Transform - Both Kafka and Rabbit binders
Log - Kafka binder
The spring-cloud-stream binder
configuration properties can be set within the applications themselves.
If not, they can be passed via deployment
properties when the stream is deployed.
For example,
dataflow:>stream create --definition "http | transform --expression=payload.toUpperCase() | log" --name mystream
dataflow:>stream deploy mystream --properties "app.http.spring.cloud.stream.bindings.output.binder=rabbit1,app.transform.spring.cloud.stream.bindings.input.binder=rabbit1,
app.transform.spring.cloud.stream.bindings.output.binder=kafka1,app.log.spring.cloud.stream.bindings.input.binder=kafka1"
One can override any of the binder configuration properties by specifying them via deployment properties.
31. Examples
31.1. Simple Stream Processing
As an example of a simple processing step, we can transform the payload of the HTTP posted data to upper case using the stream definitions
http | transform --expression=payload.toUpperCase() | log
To create this stream enter the following command in the shell
dataflow:> stream create --definition "http | transform --expression=payload.toUpperCase() | log" --name mystream --deploy
Posting some data (using a shell command)
dataflow:> http post --target http://localhost:1234 --data "hello"
Will result in an uppercased 'HELLO' in the log
2016-06-01 09:54:37.749 INFO 80083 --- [ kafka-binder-] log.sink : HELLO
31.2. Stateful Stream Processing
To demonstrate the data partitioning functionality, let’s deploy the following stream with Kafka as the binder.
dataflow:>stream create --name words --definition "http --server.port=9900 | splitter --expression=payload.split(' ') | log"
Created new stream 'words'
dataflow:>stream deploy words --properties "app.splitter.producer.partitionKeyExpression=payload,deployer.log.count=2"
Deployed stream 'words'
dataflow:>http post --target http://localhost:9900 --data "How much wood would a woodchuck chuck if a woodchuck could chuck wood"
> POST (text/plain;Charset=UTF-8) http://localhost:9900 How much wood would a woodchuck chuck if a woodchuck could chuck wood
> 202 ACCEPTED
You’ll see the following in the server logs.
2016-06-05 18:33:24.982 INFO 58039 --- [nio-9393-exec-9] o.s.c.d.spi.local.LocalAppDeployer : deploying app words.log instance 0
Logs will be in /var/folders/c3/ctx7_rns6x30tq7rb76wzqwr0000gp/T/spring-cloud-dataflow-694182453710731989/words-1465176804970/words.log
2016-06-05 18:33:24.988 INFO 58039 --- [nio-9393-exec-9] o.s.c.d.spi.local.LocalAppDeployer : deploying app words.log instance 1
Logs will be in /var/folders/c3/ctx7_rns6x30tq7rb76wzqwr0000gp/T/spring-cloud-dataflow-694182453710731989/words-1465176804970/words.log
Review the words.log instance 0
logs:
2016-06-05 18:35:47.047 INFO 58638 --- [ kafka-binder-] log.sink : How
2016-06-05 18:35:47.066 INFO 58638 --- [ kafka-binder-] log.sink : chuck
2016-06-05 18:35:47.066 INFO 58638 --- [ kafka-binder-] log.sink : chuck
Review the words.log instance 1
logs:
2016-06-05 18:35:47.047 INFO 58639 --- [ kafka-binder-] log.sink : much
2016-06-05 18:35:47.066 INFO 58639 --- [ kafka-binder-] log.sink : wood
2016-06-05 18:35:47.066 INFO 58639 --- [ kafka-binder-] log.sink : would
2016-06-05 18:35:47.066 INFO 58639 --- [ kafka-binder-] log.sink : a
2016-06-05 18:35:47.066 INFO 58639 --- [ kafka-binder-] log.sink : woodchuck
2016-06-05 18:35:47.067 INFO 58639 --- [ kafka-binder-] log.sink : if
2016-06-05 18:35:47.067 INFO 58639 --- [ kafka-binder-] log.sink : a
2016-06-05 18:35:47.067 INFO 58639 --- [ kafka-binder-] log.sink : woodchuck
2016-06-05 18:35:47.067 INFO 58639 --- [ kafka-binder-] log.sink : could
2016-06-05 18:35:47.067 INFO 58639 --- [ kafka-binder-] log.sink : wood
This shows that payload splits that contain the same word are routed to the same application instance.
31.3. Other Source and Sink Application Types
Let’s try something a bit more complicated and swap out the time
source for something else. Another supported source type is http
, which accepts data for ingestion over HTTP POSTs. Note that the http
source accepts data on a different port from the Data Flow Server (default 8080). By default the port is randomly assigned.
To create a stream using an http
source, but still using the same log
sink, we would change the original command above to
dataflow:> stream create --definition "http | log" --name myhttpstream --deploy
which will produce the following output from the server
2016-06-01 09:47:58.920 INFO 79016 --- [io-9393-exec-10] o.s.c.d.spi.local.LocalAppDeployer : deploying app myhttpstream.log instance 0
Logs will be in /var/folders/wn/8jxm_tbd1vj28c8vj37n900m0000gn/T/spring-cloud-dataflow-912434582726479179/myhttpstream-1464788878747/myhttpstream.log
2016-06-01 09:48:06.396 INFO 79016 --- [io-9393-exec-10] o.s.c.d.spi.local.LocalAppDeployer : deploying app myhttpstream.http instance 0
Logs will be in /var/folders/wn/8jxm_tbd1vj28c8vj37n900m0000gn/T/spring-cloud-dataflow-912434582726479179/myhttpstream-1464788886383/myhttpstream.http
Note that we don’t see any other output this time until we actually post some data (using a shell command). In order to see the randomly assigned port on which the http source is listening, execute:
dataflow:> runtime apps
You should see that the corresponding http source has a url
property containing the host and port information on which it is listening. You are now ready to post to that url, e.g.:
dataflow:> http post --target http://localhost:1234 --data "hello"
dataflow:> http post --target http://localhost:1234 --data "goodbye"
and the stream will then funnel the data from the http source to the output log implemented by the log sink
2016-06-01 09:50:22.121 INFO 79654 --- [ kafka-binder-] log.sink : hello
2016-06-01 09:50:26.810 INFO 79654 --- [ kafka-binder-] log.sink : goodbye
Of course, we could also change the sink implementation. You could pipe the output to a file (file
), to hadoop (hdfs
) or to any of the other sink apps which are available. You can also define your own apps.
Streams deployed using Skipper
We will proceed with the assumption that Spring Cloud Data Flow, Spring Cloud Skipper, RDBMS, and desired messaging middleware is up and running in minikube.
$ kubectl get all
NAME READY STATUS RESTARTS AGE
po/mysql-777890292-z0dsw 1/1 Running 0 38m
po/rabbitmq-317767540-2qzrr 1/1 Running 0 38m
po/redis-4054078334-37m0l 1/1 Running 0 38m
po/scdf-server-2734071167-bjd3g 1/1 Running 0 48s
po/skipper-2408247821-50z31 1/1 Running 0 3m
...
...
To start the Data Flow Shell for the Data Flow server running in skipper
mode:
$ java -jar spring-cloud-dataflow-shell-1.3.0.RC1.jar --dataflow.mode=skipper
If the Data Flow Server and shell are not running on the same host, point the shell to the Data Flow server URL:
server-unknown:>dataflow config server http://dataflow-server.cfapps.io
Successfully targeted http://dataflow-server.cfapps.io
dataflow:>
Alternatively, pass in the command line option --dataflow.uri
. The shell’s command line option `--help1 shows what is available.
Verify the registered platforms in Skipper.
dataflow:>stream platform-list
╔════════╤══════════╤════════════════════════════════════════════════════════════════════════════════════════════════╗
║ Name │ Type │ Description ║
╠════════╪══════════╪════════════════════════════════════════════════════════════════════════════════════════════════╣
║minikube│kubernetes│master url = [https://kubernetes.default.svc/], namespace = [default], api version = [v1] ║
╚════════╧══════════╧════════════════════════════════════════════════════════════════════════════════════════════════╝
Let’s start with deploying a stream with the time-source
pointing to 1.2.0.RELEASE and log-sink
pointing
to 1.1.0.RELEASE. The goal is to rolling upgrade the log-sink
application to 1.2.0.RELEASE.
dataflow:>app register --name time --type source --uri docker:springcloudstream/time-source-rabbit:1.2.0.RELEASE --force
Successfully registered application 'source:time'
dataflow:>app register --name log --type sink --uri docker:springcloudstream/log-sink-rabbit:1.1.0.RELEASE --force
Successfully registered application 'sink:log'
dataflow:>app info source:time
Information about source application 'time':
Resource URI: docker:springcloudstream/time-source-rabbit:1.2.0.RELEASE
dataflow:>app info sink:log
Information about sink application 'log':
Resource URI: docker:springcloudstream/log-sink-rabbit:1.1.0.RELEASE
-
Create stream.
dataflow:>stream create foo --definition "time | log" Created new stream 'foo'
-
Deploy stream.
dataflow:>stream deploy foo --platformName minikube Deployment request has been sent for stream 'foo'
While deploying the stream, we are supplying
--platformName
and that indicates the platform repository (i.e.,minikube
) to use when deploying the stream applications via Skipper. -
List pods.
$ kubectl get all NAME READY STATUS RESTARTS AGE po/foo-log-v1-0-2k4r8 1/1 Running 0 2m po/foo-time-v1-qhdqq 1/1 Running 0 2m po/mysql-777890292-z0dsw 1/1 Running 0 49m po/rabbitmq-317767540-2qzrr 1/1 Running 0 49m po/redis-4054078334-37m0l 1/1 Running 0 49m po/scdf-server-2734071167-bjd3g 1/1 Running 0 12m po/skipper-2408247821-50z31 1/1 Running 0 15m ... ...
-
Verify logs.
$ kubectl -f po/foo-log-v1-0-2k4r8 ... ... 2017-10-30 22:59:04.966 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 22:59:04 2017-10-30 22:59:05.968 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 22:59:05 2017-10-30 22:59:07.000 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 22:59:06
-
Verify the stream history.
dataflow:>stream history --name foo ╔═══════╤════════════════════════════╤════════╤════════════╤═══════════════╤════════════════╗ ║Version│ Last updated │ Status │Package Name│Package Version│ Description ║ ╠═══════╪════════════════════════════╪════════╪════════════╪═══════════════╪════════════════╣ ║1 │Mon Oct 30 16:18:28 PDT 2017│DEPLOYED│foo │1.0.0 │Install complete║ ╚═══════╧════════════════════════════╧════════╧════════════╧═══════════════╧════════════════╝
-
Verify the package manifest. The
log-sink
should be at 1.1.0.RELEASE.dataflow:>stream manifest --name foo --- # Source: log.yml apiVersion: skipper.spring.io/v1 kind: SpringCloudDeployerApplication metadata: name: log spec: resource: docker:springcloudstream/log-sink-rabbit version: 1.1.0.RELEASE applicationProperties: spring.metrics.export.triggers.application.includes: integration** spring.cloud.dataflow.stream.app.label: log spring.cloud.stream.metrics.key: foo.log.${spring.cloud.application.guid} spring.cloud.stream.bindings.input.group: foo spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.* spring.cloud.stream.bindings.applicationMetrics.destination: metrics spring.cloud.dataflow.stream.name: foo spring.cloud.dataflow.stream.app.type: sink spring.cloud.stream.bindings.input.destination: foo.time deploymentProperties: spring.cloud.deployer.indexed: true spring.cloud.deployer.group: foo --- # Source: time.yml apiVersion: skipper.spring.io/v1 kind: SpringCloudDeployerApplication metadata: name: time spec: resource: docker:springcloudstream/time-source-rabbit version: 1.2.0.RELEASE applicationProperties: spring.metrics.export.triggers.application.includes: integration** spring.cloud.dataflow.stream.app.label: time spring.cloud.stream.metrics.key: foo.time.${spring.cloud.application.guid} spring.cloud.stream.bindings.output.producer.requiredGroups: foo spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.* spring.cloud.stream.bindings.applicationMetrics.destination: metrics spring.cloud.stream.bindings.output.destination: foo.time spring.cloud.dataflow.stream.name: foo spring.cloud.dataflow.stream.app.type: source deploymentProperties: spring.cloud.deployer.group: foo
-
Let’s update
log-sink
from 1.1.0.RELEASE to 1.2.0.RELEASEdataflow:>stream update --name foo --properties version.log=1.2.0.RELEASE Update request has been sent for stream 'foo'
-
List pods.
$ kubectl get all NAME READY STATUS RESTARTS AGE po/foo-log-v1-0-2k4r8 1/1 Terminating 0 3m po/foo-log-v2-0-fjnlt 0/1 Running 0 9s po/foo-time-v1-qhdqq 1/1 Running 0 3m po/mysql-777890292-z0dsw 1/1 Running 0 51m po/rabbitmq-317767540-2qzrr 1/1 Running 0 51m po/redis-4054078334-37m0l 1/1 Running 0 51m po/scdf-server-2734071167-bjd3g 1/1 Running 0 14m po/skipper-2408247821-50z31 1/1 Running 0 16m ... ...
Notice that there are two versions of the
log-sink
applications. Thepo/foo-log-v1-0-2k4r8
pod is going down and the newly spawnedpo/foo-log-v2-0-fjnlt
pod is bootstrapping. The version number is incremented and the version-number (v2
) is included in the new application name. -
Once the new pod is up and running, let’s verify the logs.
$ kubectl -f po/foo-log-v2-0-fjnlt ... ... 2017-10-30 23:24:30.016 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 23:24:30 2017-10-30 23:24:31.017 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 23:24:31 2017-10-30 23:24:32.018 INFO 1 --- [ foo.time.foo-1] log-sink : 10/30/17 23:24:32
-
Let’s look at the updated package manifest persisted in Skipper. We should now be seeing
log-sink
at 1.2.0.RELEASE.dataflow:>stream manifest --name foo --- # Source: log.yml apiVersion: skipper.spring.io/v1 kind: SpringCloudDeployerApplication metadata: name: log spec: resource: docker:springcloudstream/log-sink-rabbit version: 1.2.0.RELEASE applicationProperties: spring.metrics.export.triggers.application.includes: integration** spring.cloud.dataflow.stream.app.label: log spring.cloud.stream.metrics.key: foo.log.${spring.cloud.application.guid} spring.cloud.stream.bindings.input.group: foo spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.* spring.cloud.stream.bindings.applicationMetrics.destination: metrics spring.cloud.dataflow.stream.name: foo spring.cloud.dataflow.stream.app.type: sink spring.cloud.stream.bindings.input.destination: foo.time deploymentProperties: spring.cloud.deployer.indexed: true spring.cloud.deployer.group: foo spring.cloud.deployer.count: 1 --- # Source: time.yml apiVersion: skipper.spring.io/v1 kind: SpringCloudDeployerApplication metadata: name: time spec: resource: docker:springcloudstream/time-source-rabbit version: 1.2.0.RELEASE applicationProperties: spring.metrics.export.triggers.application.includes: integration** spring.cloud.dataflow.stream.app.label: time spring.cloud.stream.metrics.key: foo.time.${spring.cloud.application.guid} spring.cloud.stream.bindings.output.producer.requiredGroups: foo spring.cloud.stream.metrics.properties: spring.application.name,spring.application.index,spring.cloud.application.*,spring.cloud.dataflow.* spring.cloud.stream.bindings.applicationMetrics.destination: metrics spring.cloud.stream.bindings.output.destination: foo.time spring.cloud.dataflow.stream.name: foo spring.cloud.dataflow.stream.app.type: source deploymentProperties: spring.cloud.deployer.group: foo
-
Verify stream history for the latest updates.
dataflow:>stream history --name foo ╔═══════╤════════════════════════════╤════════╤════════════╤═══════════════╤════════════════╗ ║Version│ Last updated │ Status │Package Name│Package Version│ Description ║ ╠═══════╪════════════════════════════╪════════╪════════════╪═══════════════╪════════════════╣ ║2 │Mon Oct 30 16:21:55 PDT 2017│DEPLOYED│foo │1.0.0 │Upgrade complete║ ║1 │Mon Oct 30 16:18:28 PDT 2017│DELETED │foo │1.0.0 │Delete complete ║ ╚═══════╧════════════════════════════╧════════╧════════════╧═══════════════╧════════════════╝
-
Rolling-back to the previous version is just a command away.
dataflow:>stream rollback --name foo Rollback request has been sent for the stream 'foo' ... ... dataflow:>stream history --name foo ╔═══════╤════════════════════════════╤════════╤════════════╤═══════════════╤════════════════╗ ║Version│ Last updated │ Status │Package Name│Package Version│ Description ║ ╠═══════╪════════════════════════════╪════════╪════════════╪═══════════════╪════════════════╣ ║3 │Mon Oct 30 16:22:51 PDT 2017│DEPLOYED│foo │1.0.0 │Upgrade complete║ ║2 │Mon Oct 30 16:21:55 PDT 2017│DELETED │foo │1.0.0 │Delete complete ║ ║1 │Mon Oct 30 16:18:28 PDT 2017│DELETED │foo │1.0.0 │Delete complete ║ ╚═══════╧════════════════════════════╧════════╧════════════╧═══════════════╧════════════════╝
Tasks
This section goes into more detail about how you can work with Spring Cloud Task. It covers topics such as creating and running task applications.
If you’re just starting out with Spring Cloud Data Flow, you should probably read the Getting Started guide before diving into this section.
32. Introduction
A task executes a process on demand. In this case a task is a
Spring Boot application that is annotated with
@EnableTask
. Hence a user launches a task that performs a certain process, and once
complete the task ends. An example of a task would be a boot application that exports
data from a JDBC repository to an HDFS instance. Tasks record the start time and the end
time as well as the boot exit code in a relational database. The task implementation is
based on the Spring Cloud Task project.
33. The Lifecycle of a Task
Before we dive deeper into the details of creating Tasks, we need to understand the typical lifecycle for tasks in the context of Spring Cloud Data Flow:
-
Creating a Task Application
-
Registering a Task Application
-
Creating a Task Definition
-
Launching a Task
-
Reviewing Task Executions
-
Destroying a Task Definition
33.1. Creating a Task Application
While Spring Cloud Task does provide a number of out of the box applications (via the spring-cloud-task-app-starters), most task applications will be custom developed. In order to create a custom task application:
-
Create a new project via Spring Initializer via either the website or your IDE making sure to select the following starters:
-
Cloud Task
- This dependency is thespring-cloud-starter-task
. -
JDBC
- This is the dependency for thespring-jdbc
starter.
-
-
Within your new project, create a new class that will serve as your main class:
@EnableTask
@SpringBootApplication
public class MyTask {
public static void main(String[] args) {
SpringApplication.run(MyTask.class, args);
}
}
-
With this, you’ll need one or more
CommandLineRunner
orApplicationRunner
within your application. You can either implement your own or use the ones provided by Spring Boot (there is one for running batch jobs for example). -
Packaging your application up via Spring Boot into an über jar is done via the standard Boot conventions.
-
The packaged application can be registered and deployed as noted below.
33.1.1. Task Database Configuration
When launching a task application be sure that the database driver that is being used by Spring Cloud Data Flow is also a dependency on the task application. For example if your Spring Cloud Data Flow is set to use Postgresql, be sure that the task application also has Postgresql as a dependency.
When executing tasks externally (i.e. command line) and you wish for Spring Cloud Data Flow to show the TaskExecutions in its UI, be sure that common datasource settings are shared among the both. By default Spring Cloud Task will use a local H2 instance and the execution will not be recorded to the database used by Spring Cloud Data Flow. |
33.2. Registering a Task Application
Register a Task App with the App Registry using the Spring Cloud Data Flow Shell
app register
command. You must provide a unique name and a URI that can be
resolved to the app artifact. For the type, specify "task". Here are a few examples:
dataflow:>app register --name task1 --type task --uri maven://com.example:mytask:1.0.2
dataflow:>app register --name task2 --type task --uri file:///Users/example/mytask-1.0.2.jar
dataflow:>app register --name task3 --type task --uri http://example.com/mytask-1.0.2.jar
When providing a URI with the maven
scheme, the format should conform to the following:
maven://<groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
If you would like to register multiple apps at one time, you can store them in a properties file
where the keys are formatted as <type>.<name>
and the values are the URIs. For example, this
would be a valid properties file:
task.foo=file:///tmp/foo.jar
task.bar=file:///tmp/bar.jar
Then use the app import
command and provide the location of the properties file via --uri
:
app import --uri file:///tmp/task-apps.properties
For convenience, we have the static files with application-URIs (for both maven and docker) available for all the out-of-the-box Task app-starters. You can point to this file and import all the application-URIs in bulk. Otherwise, as explained in previous paragraphs, you can register them individually or have your own custom property file with only the required application-URIs in it. It is recommended, however, to have a "focused" list of desired application-URIs in a custom property file.
List of available static property files:
Artifact Type | Stable Release | SNAPSHOT Release |
---|---|---|
Maven |
||
Docker |
For example, if you would like to register all out-of-the-box task applications in bulk, you can with the following command.
dataflow:>app import --uri http://bit.ly/Clark-GA-task-applications-maven
You can also pass the --local
option (which is TRUE by default) to indicate whether the
properties file location should be resolved within the shell process itself. If the location should
be resolved from the Data Flow Server process, specify --local false
.
When using either app register
or app import
, if a task app is already registered with
the provided name, it will not be overridden by default. If you would like to override the
pre-existing task app, then include the --force
option.
In some cases the Resource is resolved on the server side, whereas in others the URI will be passed to a runtime container instance where it is resolved. Consult the specific documentation of each Data Flow Server for more detail. |
33.3. Creating a Task Definition
Create a Task Definition from a Task App by providing a definition name as well as
properties that apply to the task execution. Creating a task definition can be done via
the restful API or the shell. To create a task definition using the shell, use the
task create
command to create the task definition. For example:
dataflow:>task create mytask --definition "timestamp --format=\"yyyy\""
Created new task 'mytask'
A listing of the current task definitions can be obtained via the restful API or the
shell. To get the task definition list using the shell, use the task list
command.
33.4. Launching a Task
An adhoc task can be launched via the restful API or via the shell. To launch an ad-hoc
task via the shell use the task launch
command. For example:
dataflow:>task launch mytask
Launched task 'mytask'
When a task is launched, any properties that need to be passed as the command line arguments to the task application can be set when launching the task as follows:
dataflow:>task launch mytask --arguments "--server.port=8080,--foo=bar"
Additional properties meant for a TaskLauncher
itself can be passed
in using a --properties
option. Format of this option is a comma
delimited string of properties prefixed with app.<task definition
name>.<property>
. Properties are passed
to TaskLauncher
as application properties and it is up to an
implementation to choose how those are passed into an actual task
application. If the property is prefixed with deployer
instead of app
it is
passed to TaskLauncher
as a deployment property and its meaning may
be TaskLauncher
implementation specific.
dataflow:>task launch mytask --properties "deployer.timestamp.foo1=bar1,app.timestamp.foo2=bar2"
33.4.1. Common application properties
In addition to configuration via DSL, Spring Cloud Data Flow provides a mechanism for setting common properties to all
the task applications that are launched by it.
This can be done by adding properties prefixed with spring.cloud.dataflow.applicationProperties.task
when starting the server.
When doing so, the server will pass all the properties, without the prefix, to the instances it launches.
For example, all the launched applications can be configured to use the properties foo
and fizz
by launching the Data Flow server
with the following options:
--spring.cloud.dataflow.applicationProperties.task.foo=bar
--spring.cloud.dataflow.applicationProperties.task.fizz=bar2
This will cause the properties foo=bar
and fizz=bar2
to be passed to all the launched applications.
Properties configured using this mechanism have lower precedence than task deployment properties.
They will be overridden if a property with the same key is specified at task launch time (e.g. app.trigger.fizz
will override the common property).
|
33.5. Reviewing Task Executions
Once the task is launched the state of the task is stored in a relational DB. The state includes:
-
Task Name
-
Start Time
-
End Time
-
Exit Code
-
Exit Message
-
Last Updated Time
-
Parameters
A user can check the status of their task executions via the restful API or by the shell.
To display the latest task executions via the shell use the task execution list
command.
To get a list of task executions for just one task definition, add --name
and
the task definition name, for example task execution list --name foo
. To retrieve full
details for a task execution use the task display
command with the id of the task execution,
for example task display --id 549
.
33.6. Destroying a Task Definition
Destroying a Task Definition will remove the definition from the definition repository.
This can be done via the restful API or via the shell. To destroy a task via the shell
use the task destroy
command. For example:
dataflow:>task destroy mytask
Destroyed task 'mytask'
The task execution information for previously launched tasks for the definition will remain in the task repository.
This will not stop any currently executing tasks for this definition, instead it just removes the task definition from the database. |
34. Subscribing to Task/Batch Events
You can also tap into various task/batch events when the task is launched.
If the task is enabled to generate task and/or batch events (with the additional dependencies spring-cloud-task-stream
and spring-cloud-stream-binder-kafka
, in the case of Kafka as the binder), those events are published during the task lifecycle.
By default, the destination names for those published events on the broker (rabbit, kafka etc.,) are the event names themselves (for instance: task-events
, job-execution-events
etc.,).
dataflow:>task create myTask --definition “myBatchJob"
dataflow:>task launch myTask
dataflow:>stream create task-event-subscriber1 --definition ":task-events > log" --deploy
You can control the destination name for those events by specifying explicit names when launching the task such as:
dataflow:>task launch myTask --properties "spring.cloud.stream.bindings.task-events.destination=myTaskEvents"
dataflow:>stream create task-event-subscriber2 --definition ":myTaskEvents > log" --deploy
The default Task/Batch event and destination names on the broker are enumerated below:
Event |
Destination |
Task events |
|
Job Execution events |
|
Step Execution events |
|
Item Read events |
|
Item Process events |
|
Item Write events |
|
Skip events |
|
35. Composed Tasks
Spring Cloud Data Flow allows a user to create a directed graph where each node of the graph is a task application. This is done by using the DSL for composed tasks. A composed task can be created via the RESTful API, the Spring Cloud Data Flow Shell, or the Spring Cloud Data Flow UI.
35.1. Configuring the Composed Task Runner
Composed tasks are executed via a task application called the Composed Task Runner.
35.1.1. Registering the Composed Task Runner
Out of the box the Composed Task Runner application is not registered with Spring Cloud Data Flow. So, to launch composed tasks we must first register the Composed Task Runner as an application with Spring Cloud Data Flow as follows:
app register --name composed-task-runner --type task --uri maven://org.springframework.cloud.task.app:composedtaskrunner-task:<DESIRED_VERSION>
You can also configure Spring Cloud Data Flow to use a different task definition
name for the composed task runner. This can be done by setting the
spring.cloud.dataflow.task.composedTaskRunnerName
property to the name
of your choice. You can then register the composed task runner application with
the name you set using that property.
35.1.2. Configuring the Composed Task Runner
The Composed Task Runner application has a dataflow.server.uri
property that is used for validation and for launching child tasks. This defaults
to localhost:9393
. If you run a distributed Spring Cloud Data Flow server, like you would do if you deploy the server on Cloud Foundry,
YARN or Kubernetes, then you need to provide the URI that can be used to access the server. You can either provide this dataflow.server.uri
property for the Composed Task Runner application when launching a composed task, or you can provide a spring.cloud.dataflow.server.uri
property
for the Spring Cloud Data Flow server when it is started. For the latter case the dataflow.server.uri
Composed Task Runner application property
will be automatically set when a composed task is launched.
In some cases you may wish to execute an instance of the Composed Task Runner via
the Task Launcher sink. In this case you must configure the Composed Task Runner
to use the same datasource that the Spring Cloud Data Flow instance is using.
The datasource properties are set via the TaskLaunchRequest
through the use
of the commandlineArguments
or the environmentProperties
. This is because, the
Composed Task Runner monitors the task_executions table to check the status of
the tasks that it is executing. Using this information from the table, it determines
how it should navigate the graph.
35.2. The Lifecycle of a Composed Task
35.2.1. Creating a Composed Task
The DSL for the composed tasks is used when creating a task definition via the task create command. For example:
dataflow:> app register --name timestamp --type task --uri maven://org.springframework.cloud.task.app:timestamp-task:<DESIRED_VERSION>
dataflow:> app register --name mytaskapp --type task --uri file:///home/tasks/mytask.jar
dataflow:> task create my-composed-task --definition "mytaskapp && timestamp"
dataflow:> task launch my-composed-task
In the example above we assume that the applications to be used by our composed task have not been registered yet. So the first two steps we register two task applications. We then create our composed task definition by using the task create command. The composed task DSL in the example above will, when launched, execute mytaskapp and then execute the timestamp application.
But before we launch the my-composed-task definition, we can view what Spring Cloud Data Flow generated for us. This can be done by executing the task list command.
dataflow:>task list
╔══════════════════════════╤══════════════════════╤═══════════╗
║ Task Name │ Task Definition │Task Status║
╠══════════════════════════╪══════════════════════╪═══════════╣
║my-composed-task │mytaskapp && timestamp│unknown ║
║my-composed-task-mytaskapp│mytaskapp │unknown ║
║my-composed-task-timestamp│timestamp │unknown ║
╚══════════════════════════╧══════════════════════╧═══════════╝
Spring Cloud Data Flow created three task definitions, one for each of the
applications that comprises our composed task (my-composed-task-mytaskapp
and
my-composed-task-timestamp
) as well as the composed task (my-composed-task
)
definition. We also see that each of the generated
names for the child tasks is comprised of the name of the composed task and
the name of the application separated by a dash -
. i.e. my-composed-task -
mytaskapp.
Task Application Parameters
The task applications that comprise the composed task definition can also contain parameters. For example:
dataflow:> task create my-composed-task --definition "mytaskapp --displayMessage=hello && timestamp --format=YYYY"
35.2.2. Launching a Composed Task
Launching a composed task is done the same way as launching a stand-alone task. i.e.
task launch my-composed-task
Once the task is launched and assuming all the tasks complete successfully you will
see three task executions when executing a task execution list
. For example:
dataflow:>task execution list
╔══════════════════════════╤═══╤════════════════════════════╤════════════════════════════╤═════════╗
║ Task Name │ID │ Start Time │ End Time │Exit Code║
╠══════════════════════════╪═══╪════════════════════════════╪════════════════════════════╪═════════╣
║my-composed-task-timestamp│713│Wed Apr 12 16:43:07 EDT 2017│Wed Apr 12 16:43:07 EDT 2017│0 ║
║my-composed-task-mytaskapp│712│Wed Apr 12 16:42:57 EDT 2017│Wed Apr 12 16:42:57 EDT 2017│0 ║
║my-composed-task │711│Wed Apr 12 16:42:55 EDT 2017│Wed Apr 12 16:43:15 EDT 2017│0 ║
╚══════════════════════════╧═══╧════════════════════════════╧════════════════════════════╧═════════╝
In the example above we see that my-compose-task launched and it also launched
the other tasks in sequential order and all of them executed successfully with
"Exit Code" as 0
.
Exit Statuses
The following list shows how the Exit Status will be set for each step (task) contained in the composed task following each step execution.
-
If the
TaskExecution
has anExitMessage
that will be used as theExitStatus
-
If no
ExitMessage
is present and theExitCode
is set to zero then theExitStatus
for the step will beCOMPLETED
. -
If no
ExitMessage
is present and theExitCode
is set to any non zero number then theExitStatus
for the step will beFAILED
.
35.2.3. Destroying a Composed Task
The same command used to destroy a stand-alone task is the same as destroying a composed task. The only difference is that destroying a composed task will also destroy the child tasks associated with it. For example
dataflow:>task list
╔══════════════════════════╤══════════════════════╤═══════════╗
║ Task Name │ Task Definition │Task Status║
╠══════════════════════════╪══════════════════════╪═══════════╣
║my-composed-task │mytaskapp && timestamp│COMPLETED ║
║my-composed-task-mytaskapp│mytaskapp │COMPLETED ║
║my-composed-task-timestamp│timestamp │COMPLETED ║
╚══════════════════════════╧══════════════════════╧═══════════╝
...
dataflow:>task destroy my-composed-task
dataflow:>task list
╔═════════╤═══════════════╤═══════════╗
║Task Name│Task Definition│Task Status║
╚═════════╧═══════════════╧═══════════╝
35.2.4. Stopping a Composed Task
In cases where a composed task execution needs to be stopped. This can be done via the:
-
RESTful API
-
Spring Cloud Data Flow Dashboard by selecting the Job’s tab and then clicking the stop button by the job execution that needs to be stopped.
The composed task run will be stopped
when the currently running child task completes. The step associated with the
child task that was running at the time that the composed task was stopped will
be marked as STOPPED
as well as the composed task job execution.
35.2.5. Restarting a Composed Task
In cases where a composed task fails during execution and the status of the
composed task is FAILED
then the task can be restarted. This can be done
via the:
-
RESTful API
-
Shell by launching the task using the same parameters
-
Spring Cloud Data Flow Dashboard by selecting the Job’s tab and then clicking the restart button by the job execution that needs to be restarted.
Restarting a Composed Task job that has been stopped (via the
Spring Cloud Data Flow Dashboard or RESTful API), will relaunch the
STOPPED child task, and then launch the remaining (unlaunched) child tasks
in the specified order.
|
36. Composed Tasks DSL
36.1. Conditional Execution
Conditional execution is expressed using a double ampersand symbol &&
.
This allows each task in the sequence to be launched only if the previous task
successfully completed. For example:
task create my-composed-task --definition "foo && bar"
When the composed task my-composed-task is launched, it will launch the
task foo
and if it completes successfully, then the task bar
will be
launched. If the foo
task fails, then the task bar
will not launch.
You can also use the Spring Cloud Data Flow Dashboard to create your conditional execution. By using the designer to drag and drop applications that are required, and connecting them together to create your directed graph. For example:
The diagram above is a screen capture of the directed graph as it being created using the Spring Cloud Data Flow Dashboard. We see that are 4 components in the diagram that comprise a conditional execution:
-
Start icon - All directed graphs start from this symbol. There will only be one.
-
Task icon - Represents each task in the directed graph.
-
End icon - Represents the termination of a directed graph.
-
Solid line arrow - Represents the flow conditional execution flow between:
-
Two applications
-
The start control node and an application
-
An application and the end control node
-
You can view a diagram of your directed graph by clicking the detail button next to the composed task definition on the definitions tab. |
36.2. Transitional Execution
The DSL supports fine grained control over the transitions taken during the
execution of the directed graph. Transitions are specified by providing a
condition for equality based on the exit status of the previous task.
A task transition is represented by the following symbol ->
.
36.2.1. Basic Transition
A basic transition would look like the following:
task create my-transition-composed-task --definition "foo 'FAILED' -> bar 'COMPLETED' -> baz"
In the example above foo
would launch and if it had an exit status of FAILED
,
then the bar
task would launch. If the exit status of foo
was COMPLETED
then baz
would launch. All other statuses returned by foo
will have no effect
and task would terminate normally.
Using the Spring Cloud Data Flow Dashboard to create the same "basic transition" would look like:
The diagram above is a screen capture of the directed graph as it being created using the Spring Cloud Data Flow Dashboard. Notice that there are 2 different types of connectors:
-
Dashed line - Is the line used to represent transitions from the application to one of the possible destination applications.
-
Solid line - Used to connect applications in a conditional execution or a connection between the application and a control node (end, start).
When creating a transition, link the application to each of possible destination using the connector. Once complete go to each connection and select it by clicking it. A bolt icon should appear, click that icon and enter the exit status required for that connector. The solid line for that connector will turn to a dashed line.
36.2.2. Transition With a Wildcard
Wildcards are supported for transitions by the DSL for example:
task create my-transition-composed-task --definition "foo 'FAILED' -> bar '*' -> baz"
In the example above foo
would launch and if it had an exit status of FAILED
,
then the bar
task would launch. Any exit status of foo
other than FAILED
then baz
would launch.
Using the Spring Cloud Data Flow Dashboard to create the same "transition with wildcard" would look like:
36.2.3. Transition With a Following Conditional Execution
A transition can be followed by a conditional execution so long as the wildcard is not used. For example:
task create my-transition-conditional-execution-task --definition "foo 'FAILED' -> bar 'UNKNOWN' -> baz && qux && quux"
In the example above foo
would launch and if it had an exit status of FAILED
,
then the bar
task would launch. If foo
had an exit status of UNKNOWN
then
baz
would launch. Any exit status of foo
other than FAILED
or UNKNOWN
then qux
would launch and upon successful completion quux
would launch.
Using the Spring Cloud Data Flow Dashboard to create the same "transition with conditional execution" would look like:
In this diagram we see the dashed line (transition) connecting the foo application
to the target applications, but a solid line connecting the conditional executions
between foo , qux , and quux .
|
36.3. Split Execution
Splits allow for multiple tasks within a composed task to be run in parallel.
It is denoted by using angle brackets <> to group tasks and flows that are to
be run in parallel. These tasks and flows are separated by the double pipe ||
. For example:
task create my-split-task --definition "<foo || bar || baz>"
The example above will launch tasks foo
, bar
and baz
in parallel.
Using the Spring Cloud Data Flow Dashboard to create the same "split execution" would look like:
With the task DSL a user may also execute multiple split groups in succession. For example:
task create my-split-task --definition "<foo || bar || baz> && <qux || quux>"
In the example above tasks foo
, bar
and baz
will be launched in parallel,
once they all complete then tasks qux
, quux
will be launched in parallel.
Once they complete the composed task will end. However if foo
, bar
, or
baz
fails then, the split containing qux
and quux
will not launch.
Using the Spring Cloud Data Flow Dashboard to create the same "split with multiple groups" would look like:
Notice that there is a SYNC
control node that is by the designer when
connecting two consecutive splits.
36.3.1. Split Containing Conditional Execution
A split can also have a conditional execution within the angle brackets. For example:
task create my-split-task --definition "<foo && bar || baz>"
In the example above we see that foo
and baz
will be launched in parallel,
however bar
will not launch until foo
completes successfully.
Using the Spring Cloud Data Flow Dashboard to create the same "split containing conditional execution" would look like:
37. Launching Tasks from a Stream
You can launch a task from a stream by using one of the available task-launcher
sinks. Currently the platforms supported
via the task-launcher
sinks are
local,
Cloud Foundry, and
Yarn.
task-launcher-local is meant for development purposes only.
|
A task-launcher
sink expects a message containing a TaskLaunchRequest object in its payload. From the TaskLaunchRequest
object the task-launcher
will obtain the URI of the artifact to be launched as well as the environment properties, command line arguments, deployment properties and application name to be used by the task.
The task-launcher-local can be added to the available sinks by executing the app register command as follows (for the Rabbit Binder):
app register --name task-launcher-local --type sink --uri maven://org.springframework.cloud.stream.app:task-launcher-local-sink-rabbit:jar:1.2.0.RELEASE
In the case of a maven based task that is to be launched, the task-launcher
application is responsible for downloading the artifact. You must configure the task-launcher
with the appropriate configuration of Maven Properties such as --maven.remote-repositories.repo1.url=http://repo.spring.io/libs-milestone"
to resolve artifacts, in this case against a milestone repo. Note that this repo can be different than the one used to register the task-launcher
application itself.
37.1. TriggerTask
One way to launch a task using the task-launcher
is to use the triggertask source. The triggertask
source
will emit a message with a TaskLaunchRequest
object containing the required launch information.
The triggertask
can be added to the available sources by executing the app register command as follows (for the Rabbit Binder):
app register --type source --name triggertask --uri maven://org.springframework.cloud.stream.app:triggertask-source-rabbit:1.2.0.RELEASE
An example of this would be to launch the timestamp task once every 60 seconds, the stream to implement this would look like:
stream create foo --definition "triggertask --triggertask.uri=maven://org.springframework.cloud.task.app:timestamp-task:jar:1.2.0.RELEASE --trigger.fixed-delay=60 --triggertask.environment-properties=spring.datasource.url=jdbc:h2:tcp://localhost:19092/mem:dataflow,spring.datasource.username=sa | task-launcher-local --maven.remote-repositories.repo1.url=http://repo.spring.io/libs-release" --deploy
If you execute runtime apps
you can find the log file for the task launcher sink. Tailing that file you can find the log file for the launched tasks. The setting of triggertask.environment-properties
is so that all the task executions can be collected in the same H2 database used in the local version of the Data Flow Server. You can then see the list of task executions using the shell command task execution list
dataflow:>task execution list
╔════════════════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗
║ Task Name │ID│ Start Time │ End Time │Exit Code║
╠════════════════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣
║timestamp-task_26176│4 │Tue May 02 12:13:49 EDT 2017│Tue May 02 12:13:49 EDT 2017│0 ║
║timestamp-task_32996│3 │Tue May 02 12:12:49 EDT 2017│Tue May 02 12:12:49 EDT 2017│0 ║
║timestamp-task_58971│2 │Tue May 02 12:11:50 EDT 2017│Tue May 02 12:11:50 EDT 2017│0 ║
║timestamp-task_13467│1 │Tue May 02 12:10:50 EDT 2017│Tue May 02 12:10:50 EDT 2017│0 ║
╚════════════════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝
37.2. TaskLaunchRequest-transform
Another option to start a task using the task-launcher
would be to create a stream using the
Tasklaunchrequest-transform processor to translate a message payload to a TaskLaunchRequest
.
The tasklaunchrequest-transform
can be added to the available processors by executing the app register command as follows (for the Rabbit Binder):
app register --type processor --name tasklaunchrequest-transform --uri maven://org.springframework.cloud.stream.app:tasklaunchrequest-transform-processor-rabbit:1.2.0.RELEASE
For example:
stream create task-stream --definition "http --port=9000 | tasklaunchrequest-transform --uri=maven://org.springframework.cloud.task.app:timestamp-task:jar:1.2.0.RELEASE | task-launcher-local --maven.remote-repositories.repo1.url=http://repo.spring.io/libs-release"
37.3. Launching a Composed Task From a Stream
A composed task can be launched using one of the task-launcher
sinks as discussed
here. Since we will be using
the ComposedTaskRunner
directly we will need to setup the task definitions it
will use prior to the creation of the composed task launching stream. So let’s
say that we wanted to create the following composed task definition AAA && BBB
.
The first step would be to create the task definitions. For example:
task create AAA --definition "timestamp"
task create BBB --definition "timestamp"
Now that the task definitions we need for composed task definition are ready, we
need to create a stream that will launch ComposedTaskRunner
.
So in this case we will create a stream that has a trigger that will emit a message
once every 30 seconds, a transformer that will create a TaskLaunchRequest
for
each message received, and a task-launcher-local
sink that will launch a
the ComposedTaskRunner
on our local machine. The stream should look something like this:
stream create ctr-stream --definition "time --fixed-delay=30 | tasklaunchrequest-transform --uri=maven://org.springframework.cloud.task.app:composedtaskrunner-task:<current release> --command-line-arguments='--graph=AAA&&BBB --increment-instance-enabled=true --spring.datasource.url=...' | task-launcher-local"
In the example above we see that the tasklaunchrequest-transform
is establishing
2 primary components:
-
uri - the URI of the
ComposedTaskRunner
that will be used. -
command-line-arguments - that configure the
ComposedTaskRunner
.
For now let’s focus on the configuration that is required to launch the
ComposedTaskRunner
:
-
graph - this is the graph that is to be executed by the
ComposedTaskRunner
. In this case it isAAA&&BBB
-
increment-instance-enabled - this allows each execution of
ComposedTaskRunner
to be unique.ComposedTaskRunner
is built using Spring Batch, and thus each we will want a new Job Instance for each launch of theComposedTaskRunner
. To do this we set the increment-instance-enabled to betrue
. -
spring.datasource.* - the datasource that is used by Spring Cloud Data Flow which allows the user to track the tasks launched by the
ComposedTaskRunner
and the state of the job execution. Also this is so that theComposedTaskRunner
can track the state of the tasks it launched and update its state.
Releases of ComposedTaskRunner can be found
here
|
Dashboard
This section describe how to use the Dashboard of Spring Cloud Data Flow.
38. Introduction
Spring Cloud Data Flow provides a browser-based GUI and it currently includes 6 tabs:
-
Apps Lists all available applications and provides the control to register/unregister them
-
Runtime Provides the Data Flow cluster view with the list of all running applications
-
Streams List, create, deploy, and destroy Stream Definitions
-
Tasks List, create, launch and destroy Task Definitions
-
Jobs Perform Batch Job related functions
-
Analytics Create data visualizations for the various analytics applications
Upon starting Spring Cloud Data Flow, the Dashboard is available at:
http://<host>:<port>/dashboard
For example: http://localhost:9393/dashboard
If you have enabled https, then it will be located at https://localhost:9393/dashboard
.
If you have enabled security, a login form is available at http://localhost:9393/dashboard/#/login
.
The default Dashboard server port is 9393
|
39. Apps
The Apps section of the Dashboard lists all the available applications and provides the control to register/unregister them (if applicable). It is possible to import a number of applications at once using the Bulk Import Applications action.
39.1. Bulk Import of Applications
The bulk import applications page provides numerous options for defining and importing a set of applications in one go. For bulk import the application definitions are expected to be expressed in a properties style:
<type>.<name> = <coordinates>
For example:
task.timestamp=maven://org.springframework.cloud.task.app:timestamp-task:1.2.0.RELEASE
processor.transform=maven://org.springframework.cloud.stream.app:transform-processor-rabbit:1.2.0.RELEASE
At the top of the bulk import page an Uri can be specified that points to a properties file stored elsewhere, it should contain properties formatted as above. Alternatively, using the textbox labeled Apps as Properties it is possible to directly list each property string. Finally, if the properties are stored in a local file the Select Properties File option will open a local file browser to select the file. After setting your definitions via one of these routes, click Import.
At the bottom of the page there are quick links to the property files for common groups of stream apps and task apps. If those meet your needs, simply select your appropriate variant (rabbit, kafka, docker, etc) and click the Import action on those lines to immediately import all those applications.
40. Runtime
The Runtime section of the Dashboard application shows the Spring Cloud Data Flow cluster view with the list of all running applications. For each runtime app the state of the deployment and the number of deployed instances is shown. A list of the used deployment properties is available by clicking on the app id.
41. Streams
The Streams section of the Dashboard provides the Definitions tab that provides a listing of Stream definitions. There you have the option to deploy or undeploy those stream definitions. Additionally you can remove the definition by clicking on destroy. Each row includes an arrow on the left, which can be clicked to see a visual representation of the definition. Hovering over the boxes in the visual representation will show more details about the apps including any options passed to them. In this screenshot the timer stream has been expanded to show the visual representation:
If the details button is clicked the view will change to show a visual representation of that stream and also any related streams. In the above example, if clicking details for the timer stream, the view will change to the one shown below which clearly shows the relationship between the three streams (two of them are tapping into the timer stream).
42. Create Stream
The Create Stream section of the Dashboard includes the Spring Flo designer tab that provides the canvas application, offering a interactive graphical interface for creating data pipelines.
In this tab, you can:
-
Create, manage, and visualize stream pipelines using DSL, a graphical canvas, or both
-
Write pipelines via DSL with content-assist and auto-complete
-
Use auto-adjustment and grid-layout capabilities in the GUI for simpler and interactive organization of pipelines
Watch this screencast that highlights some of the "Flo for Spring Cloud Data Flow" capabilities. Spring Flo wiki includes more detailed content on core Flo capabilities.
43. Tasks
The Tasks section of the Dashboard currently has three tabs:
-
Apps
-
Definitions
-
Executions
43.1. Apps
Apps encapsulate a unit of work into a reusable component. Within the Data Flow runtime environment Apps allow users to create definitions for Streams as well as Tasks. Consequently, the Apps tab within the Tasks section allows users to create Task definitions.
You will also use this tab to create Batch Jobs. |
On this screen you can perform the following actions:
-
View details such as the task app options.
-
Create a Task Definition from the respective App.
43.1.1. Create a Task Definition from a selected Task App
On this screen you can create a new Task Definition. As a minimum you must provide a name for the new definition. You will also have the option to specify various properties that are used during the deployment of the app.
Each parameter is only included if the Include checkbox is selected. |
43.1.2. View Task App Details
On this page you can view the details of a selected task app, including the list of available options (properties) for that app.
43.2. Definitions
This page lists the Data Flow Task definitions and provides actions to launch or destroy those tasks. It also provides a shortcut operation to define one or more tasks using simple textual input, indicated by the bulk define tasks button.
43.2.1. Creating Task Definitions using the bulk define interface
After pressing bulk define tasks, the following screen will be shown.
It includes a textbox where one or more definitions can be entered and then various actions performed on those definitions. The required input text format for task definitions is very basic, each line should be of the form:
<task-definition-name> = <task-application> <options>
For example:
demo-timestamp = timestamp --format=hhmmss
After entering any data a validator will run asynchronously to verify both the syntax and that the application name entered is a valid application and it supports the options specified. If validation fails the editor will show the errors with more information via tooltips.
To make it easier to enter definitions into the text area, content assist is supported. Pressing Ctrl+Space will invoke content assist to suggest simple task names (based on the line on which it is invoked), task applications and task application options. Press ESCape to close the content assist window without taking a selection.
If the validator should not verify the applications or the options (for example if specifying non-whitelisted options to the applications) then turn off that part of validation by toggling the checkbox off on the Verify Apps button - the validator will then only perform syntax checking. When correctly validated, the create button will be clickable and on pressing it the UI will proceed to create each task definition. If there are any errors during creation then after creation finishes the editor will show any lines of input, as it cannot be used in task definitions. These can then be fixed up and creation repeated. There is an import file button to open a file browser on the local file system if the definitions are in a file and it is easier to import than copy/paste.
Bulk loading of composed task definitions is not currently supported. |
43.2.2. Creating Composed Task Definitions
The dashboard includes the Create Composed Task tab that provides the canvas application, offering a interactive graphical interface for creating composed tasks.
In this tab, you can:
-
Create and visualize composed tasks using DSL, a graphical canvas, or both
-
Use auto-adjustment and grid-layout capabilities in the GUI for simpler and interactive organization of the composed task
43.2.3. Launching Tasks
Once the task definition is created, they can be launched through the Dashboard
as well. Navigate to the Definitions tab. Select the Task you want to launch by
pressing Launch
.
On the following screen, you can define one or more Task parameters by entering:
-
Parameter Key
-
Parameter Value
Task parameters are not typed.
43.3. Executions
44. Jobs
The Jobs section of the Dashboard allows you to inspect Batch Jobs. The main section of the screen provides a list of Job Executions. Batch Jobs are Tasks that were executing one or more Batch Job. As such each Job Execution has a back reference to the Task Execution Id (Task Id).
In case of a failed job, you can also restart the task. When dealing with long-running Batch Jobs, you can also request to stop it.
44.1. List job executions
This page lists the Batch Job Executions and provides the option to restart or stop a specific job execution, provided the operation is available. Furthermore, you have the option to view the Job execution details.
The list of Job Executions also shows the state of the underlying Job Definition. Thus, if the underlying definition has been deleted, deleted will be shown.
44.1.1. Job execution details
The Job Execution Details screen also contains a list of the executed steps. You can further drill into the Step Execution Details by clicking onto the magnifying glass.
44.1.2. Step execution details
On the top of the page, you will see progress indicator the respective step, with the option to refresh the indicator. Furthermore, a link is provided to view the step execution history.
The Step Execution details screen provides a complete list of all Step Execution Context key/value pairs.
In case of exceptions, the Exit Description field will contain additional error information. Please be aware, though, that this field can only have a maximum of 2500 characters. Therefore, in case of long exception stacktraces, trimming of error messages may occur. In that case, please refer to the server log files for further details. |
44.1.3. Step Execution Progress
On this screen, you can see a progress bar indicator in regards to the execution of the current step. Under the Step Execution History, you can also view various metrics associated with the selected step such as duration, read counts, write counts etc.
45. Analytics
The Analytics section of the Dashboard provided data visualization capabilities for the various analytics applications available in Spring Cloud Data Flow:
-
Counters
-
Field-Value Counters
-
Aggregate Counters
For example, if you create a stream with a Counter application, you can now easily create the corresponding graph from within the Dashboard tab:
-
Under
Metric Type
, selectCounters
from the select box -
Under
Stream
, selecttweetcount
-
Under
Visualization
, select the desired chart option,Bar Chart
Using the icons to the right, you can add additional charts to the Dashboard, re-arange the order of created dashboards or remove data visualizations.
REST API Guide
Appendices
Having trouble with Spring Cloud Data Flow, We’d like to help!
-
Ask a question - we monitor stackoverflow.com for questions tagged with
spring-cloud-dataflow
. -
Report bugs with Spring Cloud Data Flow at github.com/spring-cloud/spring-cloud-dataflow/issues.
-
Report bugs with Spring Cloud Data Flow for Kubernetes at github.com/spring-cloud/spring-cloud-dataflow-server-kubernetes/issues.
Appendix A: ‘How-to’ guides
A.1. Logging
Spring Cloud Data Flow is built upon several Spring projects, but ultimately the dataflow-server is a Spring Boot app, so the logging techniques that apply to any Spring Boot application are applicable here as well.
While troubleshooting, following are the two primary areas where enabling the DEBUG logs could be useful.
A.1.1. Deployment Logs
Spring Cloud Data Flow builds upon Spring Cloud Deployer SPI and the platform specific dataflow-server uses the respective SPI implementations. Specifically, if we were to troubleshoot deployment specific issues; such as the network errors, it’d be useful to enable the DEBUG logs at the underlying deployer and the libraries used by it.
-
For instance, if you’d like to enable DEBUG logs for the kubernetes-deployer, you’d be starting the server with following environment variable set.
LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_CLOUD_DEPLOYER_SPI_KUBERNETES=DEBUG
A.1.2. Application Logs
The streaming applications in Spring Cloud Data Flow are Spring Boot applications and they can be independently setup with logging configurations.
For instance, if you’d have to troubleshoot the header
and payload
specifics that are being passed
around source, processor and sink channels, you’d be deploying the stream with the following
options.
dataflow:>stream create foo --definition "http --logging.level.org.springframework.integration=DEBUG | transform --logging.level.org.springframework.integration=DEBUG | log --logging.level.org.springframework.integration=DEBUG" --deploy
(where, org.springframework.integration
is the global package for everything Spring Integration related,
which is responsible for messaging channels)
These properties can also be specified via deployment
properties when deploying the stream.
dataflow:>stream deploy foo --properties "app.*.logging.level.org.springframework.integration=DEBUG"
Appendix B: Data Flow Template
As described in the previous chapter, Spring Cloud Data Flow’s functionality is completely exposed via REST endpoints. While you can use those endpoints directly, Spring Cloud Data Flow also provides a Java-based API, which makes using those REST endpoints even easier.
The central entrypoint is the DataFlowTemplate
class in package org.springframework.cloud.dataflow.rest.client
.
This class implements the interface DataFlowOperations
and delegates to sub-templates
that provide the specific functionality for each feature-set:
Interface | Description |
---|---|
StreamOperations |
REST client for stream operations |
CounterOperations |
REST client for counter operations |
FieldValueCounterOperations |
REST client for field value counter operations |
AggregateCounterOperations |
REST client for aggregate counter operations |
TaskOperations |
REST client for task operations |
JobOperations |
REST client for job operations |
AppRegistryOperations |
REST client for app registry operations |
CompletionOperations |
REST client for completion operations |
RuntimeOperations |
REST Client for runtime operations |
When the DataFlowTemplate
is being initialized, the sub-templates will be discovered
via the REST relations, which are provided by HATEOAS.[1]
If a resource cannot be resolved, the respective sub-template will result in being NULL. A common cause is that Spring Cloud Data Flow offers for specific sets of features to be enabled/disabled when launching. For more information see Feature Toggles. |
B.1. Using the Data Flow Template
When using the Data Flow Template the only needed Data Flow dependency is the Spring Cloud Data Flow Rest Client:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dataflow-rest-client</artifactId>
<version>1.3.0.RC1</version>
</dependency>
With that dependency you will get the DataFlowTemplate
class as well as all needed
dependencies to make calls to a Spring Cloud Data Flow server.
When instantiating the DataFlowTemplate
, you will also pass in a RestTemplate
.
Please be aware that the needed RestTemplate
requires some additional configuration
to be valid in the context of the DataFlowTemplate
. When declaring a RestTemplate
as a bean, the following configuration will suffice:
@Bean
public static RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new VndErrorResponseErrorHandler(restTemplate.getMessageConverters()));
for(HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
final MappingJackson2HttpMessageConverter jacksonConverter =
(MappingJackson2HttpMessageConverter) converter;
jacksonConverter.getObjectMapper()
.registerModule(new Jackson2HalModule())
.addMixIn(JobExecution.class, JobExecutionJacksonMixIn.class)
.addMixIn(JobParameters.class, JobParametersJacksonMixIn.class)
.addMixIn(JobParameter.class, JobParameterJacksonMixIn.class)
.addMixIn(JobInstance.class, JobInstanceJacksonMixIn.class)
.addMixIn(ExitStatus.class, ExitStatusJacksonMixIn.class)
.addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class)
.addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class)
.addMixIn(StepExecutionHistory.class, StepExecutionHistoryJacksonMixIn.class);
}
}
return restTemplate;
}
Now you can instantiate the DataFlowTemplate
with:
DataFlowTemplate dataFlowTemplate = new DataFlowTemplate(
new URI("http://localhost:9393/"), restTemplate); (1)
1 | The URI points to the ROOT of your Spring Cloud Data Flow Server. |
Depending on your requirements, you can now make calls to the server. For instance, if you like to get a list of currently available applications you can execute:
PagedResources<AppRegistrationResource> apps = dataFlowTemplate.appRegistryOperations().list();
System.out.println(String.format("Retrieved %s application(s)",
apps.getContent().size()));
for (AppRegistrationResource app : apps.getContent()) {
System.out.println(String.format("App Name: %s, App Type: %s, App URI: %s",
app.getName(),
app.getType(),
app.getUri()));
}
Appendix C: Spring XD to SCDF
In this section you will learn all about the migration path from Spring XD to Spring Cloud Data Flow along with the tips and tricks.
C.1. Terminology Changes
Old | New |
---|---|
XD-Admin |
Server (implementations: local, cloud foundry, apache yarn, kubernetes, and apache mesos) |
XD-Container |
N/A |
Modules |
Applications |
Admin UI |
Dashboard |
Message Bus |
Binders |
Batch / Job |
Task |
C.2. Modules to Applications
If you have custom Spring XD modules, you’d have to refactor them to use Spring Cloud Stream and Spring Cloud Task annotations, with updated dependencies and built as normal Spring Boot "applications".
C.2.1. Custom Applications
-
Spring XD’s stream and batch modules are refactored into Spring Cloud Stream and Spring Cloud Task application-starters, respectively. These applications can be used as the reference while refactoring Spring XD modules
-
There are also some samples for Spring Cloud Stream and Spring Cloud Task applications for reference
-
If you’d like to create a brand new custom application, use the getting started guide for Spring Cloud Stream and Spring Cloud Task applications and as well as review the development guide
-
Alternatively, if you’d like to patch any of the out-of-the-box stream applications, you can follow the procedure here
C.2.2. Application Registration
-
Custom Stream/Task application requires being installed to a maven repository for Local, YARN, and CF implementations or as docker images, when deploying to Kubernetes and Mesos. Other than maven and docker resolution, you can also resolve application artifacts from
http
,file
, or ashdfs
coordinates -
Unlike Spring XD, you do not have to upload the application bits while registering custom applications anymore; instead, you’re expected to register the application coordinates that are hosted in the maven repository or by other means as discussed in the previous bullet
-
By default, none of the out-of-the-box applications are preloaded already. It is intentionally designed to provide the flexibility to register app(s), as you find appropriate for the given use-case requirement
-
Depending on the binder choice, you can manually add the appropriate binder dependency to build applications specific to that binder-type. Alternatively, you can follow the Spring Initialzr procedure to create an application with binder embedded in it
C.2.3. Application Properties
-
counter-sink:
-
The peripheral
redis
is not required in Spring Cloud Data Flow. If you intend to use thecounter-sink
, thenredis
becomes required, and you’re expected to have your own runningredis
cluster
-
-
field-value-counter-sink:
-
The peripheral
redis
is not required in Spring Cloud Data Flow. If you intend to use thefield-value-counter-sink
, thenredis
becomes required, and you’re expected to have your own runningredis
cluster
-
-
aggregate-counter-sink:
-
The peripheral
redis
is not required in Spring Cloud Data Flow. If you intend to use theaggregate-counter-sink
, thenredis
becomes required, and you’re expected to have your own runningredis
cluster
-
C.3. Message Bus to Binders
Terminology wise, in Spring Cloud Data Flow, the message bus implementation is commonly referred to as binders.
C.3.1. Message Bus
Similar to Spring XD, there’s an abstraction available to extend the binder interface. By default, we take the opinionated view of Apache Kafka and RabbitMQ as the production-ready binders and are available as GA releases.
C.3.2. Binders
Selecting a binder is as simple as providing the right binder dependency in the classpath. If you’re to choose Kafka as the binder, you’d register stream applications that are pre-built with Kafka binder in it. If you were to create a custom application with Kafka binder, you’d add the following dependency in the classpath.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
-
Spring Cloud Stream supports Apache Kafka, RabbitMQ and experimental Google PubSub and Solace JMS. All binder implementations are maintained and managed in their individual repositories
-
Every Stream/Task application can be built with a binder implementation of your choice. All the out-of-the-box applications are pre-built for both Kafka and Rabbit and they’re readily available for use as maven artifacts [Spring Cloud Stream / Spring Cloud Task or docker images [Spring Cloud Stream / Spring Cloud Task Changing the binder requires selecting the right binder dependency. Alternatively, you can download the pre-built application from this version of Spring Initializr with the desired “binder-starter” dependency
C.3.3. Named Channels
Fundamentally, all the messaging channels are backed by pub/sub semantics. Unlike Spring XD, the
messaging channels are backed only by topics
or topic-exchange
and there’s no representation of
queues
in the new architecture.
-
${xd.module.index}
is not supported anymore; instead, you can directly interact with named destinations -
stream.index
changes to:<stream-name>.<label/app-name>
-
for instance:
ticktock.0
changes to:ticktock.time
-
-
“topic/queue” prefixes are not required to interact with named-channels
-
for instance:
topic:foo
changes to:foo
-
for instance:
stream create stream1 --definition ":foo > log"
-
C.3.4. Directed Graphs
If you’re building non-linear streams, you could take advantage of named destinations to build directed graphs.
for instance, in Spring XD:
stream create f --definition "queue:foo > transform --expression=payload+'-foo' | log" --deploy
stream create b --definition "queue:bar > transform --expression=payload+'-bar' | log" --deploy
stream create r --definition "http | router --expression=payload.contains('a')?'queue:foo':'queue:bar'" --deploy
for instance, in Spring Cloud Data Flow:
stream create f --definition ":foo > transform --expression=payload+'-foo' | log" --deploy
stream create b --definition ":bar > transform --expression=payload+'-bar' | log" --deploy
stream create r --definition "http | router --expression=payload.contains('a')?'foo':'bar'" --deploy
C.4. Batch to Tasks
A Task by definition, is any application that does not run forever, including Spring Batch jobs, and they end/stop at some point. Task applications can be majorly used for on-demand use-cases such as database migration, machine learning, scheduled operations etc. Using Spring Cloud Task, users can build Spring Batch jobs as microservice applications.
-
Spring Batch jobs from Spring XD are being refactored to Spring Boot applications a.k.a Spring Cloud Task applications
-
Unlike Spring XD, these “Tasks” don’t require explicit deployment; instead, a task is ready to be launched directly once the definition is declared
C.5. Shell/DSL Commands
Old Command | New Command |
---|---|
module upload |
app register / app import |
module list |
app list |
module info |
app info |
admin config server |
dataflow config server |
job create |
task create |
job launch |
task launch |
job list |
task list |
job status |
task status |
job display |
task display |
job destroy |
task destroy |
job execution list |
task execution list |
runtime modules |
runtime apps |
C.6. REST-API
Old API | New API |
---|---|
/modules |
/apps |
/runtime/modules |
/runtime/apps |
/runtime/modules/{moduleId} |
/runtime/apps/{appId} |
/jobs/definitions |
/task/definitions |
/jobs/deployments |
/task/deployments |
C.7. UI / Flo
The Admin-UI is now renamed as Dashboard. The URI for accessing the Dashboard is changed from localhost:9393/admin-ui to localhost:9393/dashboard
-
(New) Apps: Lists all the registered applications that are available for use. This view includes informational details such as the URI and the properties supported by each application. You can also register/unregister applications from this view
-
Runtime: Container changes to Runtime. The notion of
xd-container
is gone, replaced by out-of-the-box applications running as autonomous Spring Boot applications. The Runtime tab displays the applications running in the runtime platforms (implementations: cloud foundry, apache yarn, apache mesos, or kubernetes). You can click on each application to review relevant details about the application such as where it is running with, and what resources etc. -
Spring Flo is now an OSS product. Flo for Spring Cloud Data Flow’s “Create Stream”, the designer-tab comes pre-built in the Dashboard
-
(New) Tasks:
-
The sub-tab “Modules” is renamed to “Apps”
-
The sub-tab “Definitions” lists all the Task definitions, including Spring Batch jobs that are orchestrated as Tasks
-
The sub-tab “Executions” lists all the Task execution details similar to Spring XD’s Job executions
-
C.8. Architecture Components
Spring Cloud Data Flow comes with a significantly simplified architecture. In fact, when compared with Spring XD, there are less peripherals that are necessary to operationalize Spring Cloud Data Flow.
C.8.1. ZooKeeper
ZooKeeper is not used in the new architecture.
C.8.2. RDBMS
Spring Cloud Data Flow uses an RDBMS instead of Redis for stream/task definitions, application registration, and for job repositories.The default configuration uses an embedded H2 instance, but Oracle, DB2, SqlServer, MySQL/MariaDB, PostgreSQL, H2, and HSQLDB databases are supported. To use Oracle, DB2 and SqlServer you will need to create your own Data Flow Server using Spring Initializr and add the appropriate JDBC driver dependency.
C.8.3. Redis
Running a Redis cluster is only required for analytics functionality. Specifically, when the counter-sink
,
field-value-counter-sink
, or aggregate-counter-sink
applications are used, it is expected to also
have a running instance of Redis cluster.
C.8.4. Cluster Topology
Spring XD’s xd-admin
and xd-container
server components are replaced by stream and task
applications themselves running as autonomous Spring Boot applications. The applications run natively
on various platforms including Cloud Foundry, Apache YARN, Apache Mesos, or Kubernetes. You can develop,
test, deploy, scale +/-, and interact with (Spring Boot) applications individually, and they can
evolve in isolation.
C.9. Central Configuration
To support centralized and consistent management of an application’s configuration properties, Spring Cloud Config client libraries have been included into the Spring Cloud Data Flow server as well as the Spring Cloud Stream applications provided by the Spring Cloud Stream App Starters. You can also pass common application properties to all streams when the Data Flow Server starts.
C.10. Distribution
Spring Cloud Data Flow is a Spring Boot application. Depending on the platform of your choice, you
can download the respective release uber-jar and deploy/push it to the runtime platform
(cloud foundry, apache yarn, kubernetes, or apache mesos). For example, if you’re running Spring
Cloud Data Flow on Cloud Foundry, you’d download the Cloud Foundry server implementation and do a
cf push
as explained in the reference guide.
C.11. Hadoop Distribution Compatibility
The hdfs-sink
application builds upon Spring Hadoop 2.4.0 release, so this application is compatible
with following Hadoop distributions.
-
Cloudera - cdh5
-
Pivotal Hadoop - phd30
-
Hortonworks Hadoop - hdp24
-
Hortonworks Hadoop - hdp23
-
Vanilla Hadoop - hadoop26
-
Vanilla Hadoop - 2.7.x (default)
C.12. YARN Deployment
Spring Cloud Data Flow can be deployed and used with Apche YARN in two different ways.
-
Deploy the server directly in a YARN cluster
-
Leverage Apache Ambari plugin to provision Spring Cloud Data Flow as a service
C.13. Use Case Comparison
Let’s review some use-cases to compare and contrast the differences between Spring XD and Spring Cloud Data Flow.
C.13.1. Use Case #1
(It is assumed both XD and SCDF distributions are already downloaded)
Description: Simple ticktock
example using local/singlenode.
Spring XD | Spring Cloud Data Flow |
---|---|
Start
|
Start a binder of your choice Start
|
Start
|
Start
|
Create
|
Create
|
Review |
Review |
C.13.2. Use Case #2
(It is assumed both XD and SCDF distributions are already downloaded)
Description: Stream with custom module/application.
Spring XD | Spring Cloud Data Flow |
---|---|
Start
|
Start a binder of your choice Start
|
Start
|
Start
|
Register custom “processor” module to transform payload to a desired format
|
Register custom “processor” application to transform payload to a desired format
|
Create a stream with custom module
|
Create a stream with custom application
|
Review results in the |
Review results by tailing the |
C.13.3. Use Case #3
(It is assumed both XD and SCDF distributions are already downloaded)
Description: Simple batch-job.
Spring XD | Spring Cloud Data Flow |
---|---|
Start
|
Start
|
Start
|
Start
|
Register custom “batch-job” module
|
Register custom “batch-job” as task application
|
Create a job with custom batch-job module
|
Create a task with custom batch-job application
|
Deploy job
|
NA |
Launch job
|
Launch task
|
Review results in the |
Review results by tailing the |
Appendix D: Building
To build the source you will need to install JDK 1.8.
The build uses the Maven wrapper so you don’t have to install a specific version of Maven. To enable the tests for Redis you should run the server before bulding. See below for more information on how to run Redis.
The main build command is
$ ./mvnw clean install
You can also add '-DskipTests' if you like, to avoid running the tests.
You can also install Maven (>=3.3.3) yourself and run the mvn command
in place of ./mvnw in the examples below. If you do that you also
might need to add -P spring if your local Maven settings do not
contain repository declarations for spring pre-release artifacts.
|
Be aware that you might need to increase the amount of memory
available to Maven by setting a MAVEN_OPTS environment variable with
a value like -Xmx512m -XX:MaxPermSize=128m . We try to cover this in
the .mvn configuration, so if you find you have to do it to make a
build succeed, please raise a ticket to get the settings added to
source control.
|
The projects that require middleware generally include a
docker-compose.yml
, so consider using
Docker Compose to run the middeware servers
in Docker containers. See the README in the
scripts demo
repository for specific instructions about the common cases of mongo,
rabbit and redis.
D.1. Documentation
There is a "full" profile that will generate documentation. You can build just the documentation by executing
$ ./mvnw clean package -DskipTests -P full -pl spring-cloud-dataflow-server-kubernetes-docs -am
D.2. Working with the code
If you don’t have an IDE preference we would recommend that you use Spring Tools Suite or Eclipse when working with the code. We use the m2eclipe eclipse plugin for maven support. Other IDEs and tools should also work without issue.
D.2.1. Importing into eclipse with m2eclipse
We recommend the m2eclipe eclipse plugin when working with eclipse. If you don’t already have m2eclipse installed it is available from the "eclipse marketplace".
Unfortunately m2e does not yet support Maven 3.3, so once the projects
are imported into Eclipse you will also need to tell m2eclipse to use
the .settings.xml
file for the projects. If you do not do this you
may see many different errors related to the POMs in the
projects. Open your Eclipse preferences, expand the Maven
preferences, and select User Settings. In the User Settings field
click Browse and navigate to the Spring Cloud project you imported
selecting the .settings.xml
file in that project. Click Apply and
then OK to save the preference changes.
Alternatively you can copy the repository settings from .settings.xml into your own ~/.m2/settings.xml .
|
D.2.2. Importing into eclipse without m2eclipse
If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command:
$ ./mvnw eclipse:eclipse
The generated eclipse projects can be imported by selecting import existing projects
from the file
menu.
Appendix E: Contributing
Spring Cloud is released under the non-restrictive Apache 2.0 license, and follows a very standard Github development process, using Github tracker for issues and merging pull requests into master. If you want to contribute even something trivial please do not hesitate, but follow the guidelines below.
E.1. Sign the Contributor License Agreement
Before we accept a non-trivial patch or pull request we will need you to sign the contributor’s agreement. Signing the contributor’s agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
E.2. Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge.
-
Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the
eclipse-code-formatter.xml
file from the Spring Cloud Build project. If using IntelliJ, you can use the Eclipse Code Formatter Plugin to import the same file. -
Make sure all new
.java
files to have a simple Javadoc class comment with at least an@author
tag identifying you, and preferably at least a paragraph on what the class is for. -
Add the ASF license header comment to all new
.java
files (copy from existing files in the project) -
Add yourself as an
@author
to the .java files that you modify substantially (more than cosmetic changes). -
Add some Javadocs and, if you change the namespace, some XSD doc elements.
-
A few unit tests would help a lot as well — someone has to do it.
-
If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project).
-
When writing a commit message please follow these conventions, if you are fixing an existing issue please add
Fixes gh-XXXX
at the end of the commit message (where XXXX is the issue number).