当前位置:   article > 正文

Kubernetes jobs:使用队列进行并行化处理

kubernetes jobs并发测试

本例子中,将运行 Kubernetes Job进行多个并行工作处理,在给定的pod里执行。

每一个 pod一旦创建,就讲从队列中取出一个工作单元,然后重复,知道队列的结束。

Here is an overview of the steps in this example:

  1. Start a storage service to hold the work queue. In this example, we use Redis to store our work items. In the previous example, we used RabbitMQ. In this example, we use Redis and a custom work-queue client library because AMQP does not provide a good way for clients to detect when a finite-length work queue is empty. In practice you would set up a store such as Redis once and reuse it for the work queues of many jobs, and other things.
  2. Create a queue, and fill it with messages. Each message represents one task to be done. In this example, a message is just an integer that we will do a lengthy computation on.
  3. Start a Job that works on tasks from the queue. The Job starts several pods. Each pod takes one task from the message queue, processes it, and repeats until the end of the queue is reached.

Before you begin

You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using Minikube, or you can use one of these Kubernetes playgrounds:

To check the version, enter kubectl version.

Starting Redis

For this example, for simplicity, we will start a single instance of Redis. See the Redis Example for an example of deploying Redis scalably and redundantly.

If you are working from the website source tree, you can go to the following directory and start a temporary Pod running Redis and a service so we can find it.

  1. $ cd content/en/examples/application/job/redis
  2. $ kubectl create -f ./redis-pod.yaml
  3. pod/redis-master created
  4. $ kubectl create -f ./redis-service.yaml
  5. service/redis created

If you’re not working from the source tree, you could also download the following files directly:

Filling the Queue with tasks

Now let’s fill the queue with some “tasks”. In our example, our tasks are just strings to be printed.

Start a temporary interactive pod for running the Redis CLI.

  1. $ kubectl run -i --tty temp --image redis --command "/bin/sh"
  2. Waiting for pod default/redis2-c7h78 to be running, status is Pending, pod ready: false
  3. Hit enter for command prompt

Now hit enter, start the redis CLI, and create a list with some work items in it.

  1. # redis-cli -h redis
  2. redis:6379> rpush job2 "apple"
  3. (integer) 1
  4. redis:6379> rpush job2 "banana"
  5. (integer) 2
  6. redis:6379> rpush job2 "cherry"
  7. (integer) 3
  8. redis:6379> rpush job2 "date"
  9. (integer) 4
  10. redis:6379> rpush job2 "fig"
  11. (integer) 5
  12. redis:6379> rpush job2 "grape"
  13. (integer) 6
  14. redis:6379> rpush job2 "lemon"
  15. (integer) 7
  16. redis:6379> rpush job2 "melon"
  17. (integer) 8
  18. redis:6379> rpush job2 "orange"
  19. (integer) 9
  20. redis:6379> lrange job2 0 -1
  21. 1) "apple"
  22. 2) "banana"
  23. 3) "cherry"
  24. 4) "date"
  25. 5) "fig"
  26. 6) "grape"
  27. 7) "lemon"
  28. 8) "melon"
  29. 9) "orange"

So, the list with key job2 will be our work queue.

Note: if you do not have Kube DNS setup correctly, you may need to change the first step of the above block to redis-cli -h $REDIS_SERVICE_HOST.

Create an Image

Now we are ready to create an image that we will run.

We will use a python worker program with a redis client to read the messages from the message queue.

A simple Redis work queue client library is provided, called rediswq.py (Download).

The “worker” program in each Pod of the Job uses the work queue client library to get work. Here it is:

application/job/redis/worker.py 09115340_fjph.svg
  1. #!/usr/bin/env python
  2. import time
  3. import rediswq
  4. host="redis"
  5. # Uncomment next two lines if you do not have Kube-DNS working.
  6. # import os
  7. # host = os.getenv("REDIS_SERVICE_HOST")
  8. q = rediswq.RedisWQ(name="job2", host="redis")
  9. print("Worker with sessionID: " + q.sessionID())
  10. print("Initial queue state: empty=" + str(q.empty()))
  11. while not q.empty():
  12. item = q.lease(lease_secs=10, block=True, timeout=2)
  13. if item is not None:
  14. itemstr = item.decode("utf=8")
  15. print("Working on " + itemstr)
  16. time.sleep(10) # Put your actual work here instead of sleep.
  17. q.complete(item)
  18. else:
  19. print("Waiting for work")
  20. print("Queue empty, exiting")

If you are working from the source tree, change directory to the content/en/examples/application/job/redis/ directory. Otherwise, download worker.py, rediswq.py, and Dockerfile files, then build the image:

docker build -t job-wq-2 .

Push the image

For the Docker Hub, tag your app image with your username and push to the Hub with the below commands. Replace <username> with your Hub username.

  1. docker tag job-wq-2 <username>/job-wq-2
  2. docker push <username>/job-wq-2

You need to push to a public repository or configure your cluster to be able to access your private repository.

If you are using Google Container Registry, tag your app image with your project ID, and push to GCR. Replace <project> with your project ID.

  1. docker tag job-wq-2 gcr.io/<project>/job-wq-2
  2. gcloud docker -- push gcr.io/<project>/job-wq-2

Defining a Job

Here is the job definition:

application/job/redis/job.yaml 09115340_fjph.svg
  1. apiVersion: batch/v1
  2. kind: Job
  3. metadata:
  4. name: job-wq-2
  5. spec:
  6. parallelism: 2
  7. template:
  8. metadata:
  9. name: job-wq-2
  10. spec:
  11. containers:
  12. - name: c
  13. image: gcr.io/myproject/job-wq-2
  14. restartPolicy: OnFailure

Be sure to edit the job template to change gcr.io/myproject to your own path.

In this example, each pod works on several items from the queue and then exits when there are no more items. Since the workers themselves detect when the workqueue is empty, and the Job controller does not know about the workqueue, it relies on the workers to signal when they are done working. The workers signal that the queue is empty by exiting with success. So, as soon as any worker exits with success, the controller knows the work is done, and the Pods will exit soon. So, we set the completion count of the Job to 1. The job controller will wait for the other pods to complete too.

Running the Job

So, now run the Job:

kubectl create -f ./job.yaml

Now wait a bit, then check on the job.

  1. $ kubectl describe jobs/job-wq-2
  2. Name: job-wq-2
  3. Namespace: default
  4. Selector: controller-uid=b1c7e4e3-92e1-11e7-b85e-fa163ee3c11f
  5. Labels: controller-uid=b1c7e4e3-92e1-11e7-b85e-fa163ee3c11f
  6. job-name=job-wq-2
  7. Annotations: <none>
  8. Parallelism: 2
  9. Completions: <unset>
  10. Start Time: Mon, 11 Jan 2016 17:07:59 -0800
  11. Pods Statuses: 1 Running / 0 Succeeded / 0 Failed
  12. Pod Template:
  13. Labels: controller-uid=b1c7e4e3-92e1-11e7-b85e-fa163ee3c11f
  14. job-name=job-wq-2
  15. Containers:
  16. c:
  17. Image: gcr.io/exampleproject/job-wq-2
  18. Port:
  19. Environment: <none>
  20. Mounts: <none>
  21. Volumes: <none>
  22. Events:
  23. FirstSeen LastSeen Count From SubobjectPath Type Reason Message
  24. --------- -------- ----- ---- ------------- -------- ------ -------
  25. 33s 33s 1 {job-controller } Normal SuccessfulCreate Created pod: job-wq-2-lglf8
  26. $ kubectl logs pods/job-wq-2-7r7b2
  27. Worker with sessionID: bbd72d0a-9e5c-4dd6-abf6-416cc267991f
  28. Initial queue state: empty=False
  29. Working on banana
  30. Working on date
  31. Working on lemon

As you can see, one of our pods worked on several work units.

Alternatives

If running a queue service or modifying your containers to use a work queue is inconvenient, you may want to consider one of the other job patterns.

If you have a continuous stream of background processing work to run, then consider running your background workers with a replicationController instead, and consider running a background processing library such as https://github.com/resque/resque.

转载于:https://my.oschina.net/u/2306127/blog/1982586

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/563788
推荐阅读
相关标签
  

闽ICP备14008679号