Samme
Samme

Reputation: 21

Run a Kubernetes Cron Job from OpenShift to call a REST endpoint Periodically

I'm doing research on how to run a Spring Batch job on RedHat OpenShift as a Kubernetes Scheduled Job. Steps have done,

1) Created a sample Spring Batch app that reads a .csv file that does simple processing and puts some data into in-memory h2 DB. The job launcher is called upon as a REST endpoint (/load). The source code can be found here. Please see the README file for the endpoint info.

2) Created the Docker Image and pushed into DockerHub

3) Deployed using that image to my OpenShift Online cluster as an app

What I want to do is,

Run a Kubernetes Cron Job from OpenShift to call /load REST endpoint which launches the SpringBatch job periodically

Can someone please guide me here on how can I achieve this?

Thank you

Samme

Upvotes: 2

Views: 7131

Answers (1)

acid_fuji
acid_fuji

Reputation: 6853

The easiest way would be to curl your /load REST endpoint. Here's a way to do that:

The Pod definition that I used as replacement for you application (for testing purposes):

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: mendhak/http-https-echo

I used this image because it sends various HTTP request properties back to client.

Create a service for pod:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  selector:
    app: myapp the selector
  ports:
    - protocol: TCP
      port: 80 #Port that service is available on
      targetPort: 80 #Port that app listens on

Create a CronJob:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: curljob
spec:
  jobTemplate:
    metadata:
      name: curljob
    spec:
      template:
        metadata:
        spec:
          containers:
          - command:
            - curl
            - http://myapp-service:80/load
            image: curlimages/curl
            imagePullPolicy: Always
            name: curljobt
          restartPolicy: OnFailure
  schedule: '*/1 * * * *'

Alternatively you can use command to launch it:

kubectl create cronjob --image curlimages/curl curljob -oyaml --schedule "*/1 * * * *" -- curl  http://myapp-service:80/load 

When "*/1 * * * *" will specify how often this CronJob would run. I`ve set it up to run every one minute. You can see more about how to setup cron job here and here

Here is the result of the kubectl logs from one of the job`s pod:

{
  "path": "/load",
  "headers": {
    "host": "myapp-service",
    "user-agent": "curl/7.68.0-DEV",
    "accept": "*/*"
  },
  "method": "GET",
  "body": "",
  "fresh": false,
  "hostname": "myapp-service",
  "ip": "::ffff:192.168.197.19",
  "ips": [],
  "protocol": "http",
  "query": {},
  "subdomains": [],
  "xhr": false,
  "os": {
    "hostname": "myapp-pod"

As you can see the application receives GET request with path: /load.

Let me know if that helps.

Upvotes: 3

Related Questions