HTTP Gateway : Invoking Celery Tasks from Java (Non Python Application) – Part #3

HTTP Gateway is the ideal way for celery tasks invocation and status polling from any non python languages like java. For this, first we have to set up a django application which would handle all the incoming requests for tasks invocation and status polling. As a first step, we need to install python virtual enviroment named env (not mandatory, But I prefer this as this wont affect python packages installed in the machine).

Step1 :
activate the virtual environment and install all required libraries like django,djecelery etc.

Step 2:
copy and paste the django app for http-gateway in this activated virtual environment,env.(I have uploaded the code for this app in github,

This app contains all tasks in file. Now run the app from this activated virtual environment using the following command :
python runserver

Now with this, our djnago app would start at localhost:8080, to which we can send rest api calls. It is likely to be getting some module not found errors at this point, in case u get them, just try to install the missing packages and libraries in this activated virtual environment. and then run the app again.

The structure of the entire app is described in the image added below :
Screenshot from 2016-07-14 18:21:27

Now we need workers to execute the tasks. So open a terminal and run the following command from the root directory of our application (env/celery-HTTPgateway),

celery worker -A tasks –loglevel=INFO

It would then list all registered tasks there. We would be able to see to tasks,

Now let’s see how we can invoke a celery task and poll its status using REST apis. These rest apis can be called from any programming languages using appropriate native apis.

For the sake of simplicity, here I am using linux curl command for simulating REST api calls.
( / at end of the url is mandatory for this command to work)

Open a terminal and run the following command,

curl -X GET http://localhost:8000/apply/tasks.hello_world/

Then you would a json data as response,

{“ok”: “true”, “task_id”: “0fc2150e-b321-4cc6-aaef-b1ce9b30e7fe”}

The respose contains the id of the invoked tasks which can be used to track its status.

Status Polling:

curl -X GET http://localhost:8000/0fc2150e-b321-4cc6-aaef-b1ce9b30e7fe/status/

{“task”: {“status”: “SUCCESS”, “result”: “Hello world………”, “id”: “0fc2150e-b321-4cc6-aaef-b1ce9b30e7fe”}}

These api would display custom states,something at which celery flower apis fails most of the time. A task named UploadTask has been written in file with a view to showcase this feature. For this, first we need to invoke the tasks and then track the status.

Task invocation :

curl -X GET http://localhost:8000/apply/tasks.UploadTask/
Response –
“ok”: “true”,
“task_id”: “cc51e093-372f-42c1-8344-c1def70c544a”

The status checking of above task, can be done :

curl -X GET http://localhost:8000/cc51e093-372f-42c1-8344-c1def70c544a/status/
“task”: {
“status”: “PROGRESS”,
“result”: {
“progress”: 0
“id”: “cc51e093-372f-42c1-8344-c1def70c544a”

References :


Invoking Celery Tasks from Java Application – Part #1

Invoking a celery task from java application is not hassle but not an easy one either.  This java celery integration was  implemented  with the help of a message broker/queue  and  what I chose for this was RabbitMQ.  There are many options out there  for message broker but I opted this as I had used it earlier with celery.

This article is based on the assumptions that  readers have a bit prior experience with celery and RabbitMQ. For a start, we can go through a very very brief introduction. (might write a few articles on celery, if time favours ..)

As we know, celery is task queue which absorbs messsags from message queues (iie here RabbitMQ ) and execute them in celery worker threads. Here, in order to trigger a celery task from java application, what we need to is, to create a rabbitMQ queue and push the messages to this queue from java application, in an appropriate format ie format that celery tasks messages adhere to ( Then We need to  define tasks and start  worker thread to execute these tasks as messages are available in this message queue, (as the java application pushes them).

Following are the steps I have done to make it working  :

1. Download java – rabbitMQ client library   from here                                                                                                                    Then extract the zip file and copy all the jar files into the root directory of the project.

2.  Now we need to write the java code to integrate RabbitMQ and push tasks messages to  specific RabbitMQ queues.          This needs to be placed in the root directory of the project where we have just copied jar files into, in the previous step.

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.AMQP;
public class Send {
public static void main(String[] argv) throws Exception {
String QUEUE_NAME = “celery”;
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = “{\”id\”: \”4cc7438e-afd4-4f8f-a2f3-f46567e7ca77\”, \”task\”: \”tasks.add\”, \”args\”: [1,2], \”kwargs\”: {}, \”retries\”: 0, \”eta\”: \”2009-11-17T12:30:56.527191\”}”;
channel.basicPublish(“”, QUEUE_NAME, new AMQP.BasicProperties.Builder()
.build(), message.getBytes(“utf-8″));
System.out.println(” [x] Sent ‘” + message + “‘”);

In this, we are sending messages to a queue named “celery” . Also the format of the message is specified in the variable message and from which it is clear that name of the task is tasks.add and arguments are 1 and 2. This is equivalent to calling add.delay(1,2). Hence bow the task message for addition has been sent to the queue celery.

3.  Now we need to define the celery task.                                                                                                                                      In the root directory of the project add following python files.


from celery import Celery
app = Celery(‘tasks’)

def add(x, y):
# return x + y
print “haiii”
print x+y

CELERY_IMPORTS = (“tasks”, )
BROKER_URL = “amqp://guest:guest@localhost:5672//”

4.  Now we can start celery worker to execute the tasks messages

From the root directory of the project open a terminal and run the following command :                                                           celery -A tasks worker –loglevel=info    

here -A stands for application name, since the argument passed in while creating celery instance is                                       tasks ( app =Celery(“tasks”) ), here our application name is tasks.

5. compile and run to push celery asks to rabbitMQ queue :

 javac -cp rabbitmq-client.jar                                                                                                                                      java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Send

Here we use the parameter -cp to keep the required jar files in class path. With this we have successfully pushed the          tasks messages to queue.

6. Now open the terminal where celery worker is started, you would get the following result.

Screenshot from 2016-05-26 17:33:31