SlideShare a Scribd company logo
1 of 35
Download to read offline
Печём пирожки с Celery
Александр Мокров
О чем доклад
Немного об очередях
Краткий обзор возможностей Celery
Использование на примере виртуальной фабрики пирожков
Очереди
Producer
queue_name
Consumer
Очереди
Producer
Consumer
Consumer
queue_name
Роутинг
Producer
Consumer
Consumer
first_queue
X
second_queue
whitewhite
black
What is task queue?
Celery: Distributed Task Queue
Celery is an asynchronous task queue/job queue based on distributed message
passing. It is focused on real-time operation, but supports scheduling as well.
The execution units, called tasks, are executed concurrently on a single or more
worker servers using multiprocessing, Eventlet, or gevent. Tasks can execute
asynchronously (in the background) or synchronously (wait until ready).
Celery is used in production systems to process millions of tasks a day.
Ask Solem Hoel
https://github.com/ask
Principal Software Engineer at Robinhood
San Francisco, CA
Staff Engineer, RabbitMQ
VMware
май 2011 – май 2013 (2 года 1 месяц)
Open source and consulting work on Celery, RabbitMQ,
Celery Дата начала: май 2009
Celery
Kombu (Messaging library for Python) 41991 (22541) lines
Billiard (Python multiprocessing fork with improvements and bugfixes) 19191(13115)
Vine (promise, async, future) 2921
Celery 104296 (37495)
Total 168399(76072)
It supports
Brokers
RabbitMQ, Redis,
MongoDB (exp), ZeroMQ (exp)
CouchDB (exp), SQLAlchemy (exp)
Django ORM (exp), Amazon SQS, (exp)
Concurrency
prefork (multiprocessing),
Eventlet, gevent
threads/single threaded
Result Stores
AMQP, Redis
memcached, MongoDB
SQLAlchemy, Django ORM
Apache Cassandra
Serialization
pickle, json, yaml, msgpack.
zlib, bzip2 compression.
Cryptographic message signing
Application
from celery import Celery
from conf import Settings
from tasks.bake_pie import BakePie
APP_NAME = 'pie_fabric'
app = Celery(APP_NAME)
app.config_from_object(Settings)
app.tasks.register(BakePie())
Settings
class Settings:
BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
$ celery -A pie_fabric worker -l INFO
-------------- celery@amokrov v4.0.0rc2 (0today8)
---- **** -----
--- * *** * -- Linux-3.19.0-61-generic-x86_64-with-Ubuntu-14.04-trusty 2016-06-24 15:52:22
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: pie_fabric:0x7efc8cd4c588
- ** ---------- .> transport: amqp://guest:**@localhost:5672//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ----
--- ***** ----- [queues]
-------------- .> celery exchange=celery(direct) key=celery
[tasks]
. bake_pie
Architecture
Client
1
Client
2
Worker
1Broker
Task Queue 1
Task Queue 2
...
Worker
2
Result Backend
send tasks
send tasks
tasks
tasks
task result
task result
get task result
get task result
Фабрика пирожков
Интерфейс
Заказ
Осуществление
заказа
Стряпание
пирога
Выпекание
пирога
Получение
ингредиентов
для теста
Ингредиенты Заготовка
Пирог
Создание
теста
Получение
начинки
Workflow
get flour
bake pie
get meat
seal pie
create
dough
order pie
get milk
get aggs
The canvas
Wokrflow primitives
● group
● chain
● chord
● map, starmap, chunks
Tasks
from celery.app.task import Task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
class GetIngredient(Task):
name = 'get_ingredients'
def run(self, ingredient_name):
logger.info('Getting {}'.format(ingredient_name))
l # код получения ингредиента
return ingredient
Workflow
from celery.app.task import Task
from celery import canvas, signature
class OrderPie(Task):
name = 'order_pie'
def run(self):
get_meat = signature('get_ingredients', args=('meat',))
...
dough_chord = canvas.chord([get_eggs, get_milk, get_flour], create_dough)
components_group = canvas.group(dough_chord, get_meat)
return (components_group | seal_pie | bake_pie).delay()
Client side
>>> from tasks.order_pie import OrderPie
>>> r = OrderPie().delay()
>>> r.id
'58c5bb47-8fb3-4d4a-b2f5-8899520b5179'
>>> r.ready()
True
>>> r.get()
[['091f9ae7-561a-4781-a4d9-47bbcb121360', [['0865f66b-b89d-4ff3-a272-1f6b01d0a11f', None],
None]], None]
>>> r.backend.get_task_meta(r.get()[0][0])
{'task_id': '091f9ae7-561a-4781-a4d9-47bbcb121360', 'children': [], 'traceback': None, 'result':
'baked pie with meat', 'status': 'SUCCESS'}
Routing
from kombu import Exchange, Queue
class Router:
def route_for_task(self, task, *args, **kwargs):
route = {'exchange': Settings.EXCHANGE.name,
'routing_key': 'common'}
if task in {'bake_pie', 'get_ingredients',
'seal_pie', 'order_pie'}:
route['routing_key'] = 'fabric'
elif task == 'create_dough':
route = {'exchange': 'dough',
'routing_key': 'dough'}
return route
Routing
class Settings:
EXCHANGE = Exchange('pie_fabric,
type='direct')
CELERY_ROUTES = (Router(),)
CELERY_QUEUES = (
Queue('pie_fabric.common', EXCHANGE,
routing_key='common'),
Queue('pie_fabric.fabric', EXCHANGE,
routing_key='fabric'),
)
--- ***** ----- [queues]
-------------- .> pie_fabric.common
exchange=pie_fabric(direct) key=common
.> pie_fabric.fabric
exchange=pie_fabric(direct) key=fabric
Second application
class Settings:
BROKER_URL = 'amqp://guest:guest@localhost:
5672//'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:
6379/0'
EXCHANGE = Exchange('dough', type='direct')
CELERY_QUEUES = (
Queue('dough', EXCHANGE,
routing_key='dough'),
)
app = Celery('dough')
app.config_from_object(Settings)
app.tasks.register(CreateDough())
$celery -A dough worker -P gevent --
concurrency=1000 -l INFO
- ** ---------- [config]
- ** ---------- .> app: dough:0x7f850ee22748
- ** ---------- .> transport: amqp://guest:
**@localhost:5672//
- ** ---------- .> results: redis://127.0.0.1:6379/0
- *** --- * --- .> concurrency: 1000 (gevent)
-- ******* ----
--- ***** ----- [queues]
-------------- .> dough exchange=dough
(direct) key=dough
[tasks]
. create_dough
Gevent
gevent is a coroutine -based Python networking library that uses greenlet to
provide a high-level synchronous API on top of the libev event loop
gevent.monkey – Make the standard library cooperative
def _patch_gevent():
from gevent import monkey, signal as gsignal, version_info
monkey.patch_all()
Polling
def run(self, *ingredients):
logger.info('Ingredients: {}'.format(ingredients))
id = create_dough(ingredients) # Отправка запроса на приготовление теста
while True:
time.sleep(polling_timeout)
if ready(id): # Проверяем готово ли тесто
dough = get_dough(id) # Если готово, то забираем
return dough
Calling Tasks
apply
Execute this task locally, by blocking until the task returns.
apply_async
Apply tasks asynchronously by sending a message.
delay
Shortcut to send a task message, but does not support execution options.
retry
Retry the task.
Options
Linking (callbacks/errbacks)
link
link_error
ETA and countdown
countdown
eta
Expiration
expires
Retry
retry=True,
retry_policy={
'max_retries': 3,
'interval_start': 0,
'interval_step': 0.2,
'interval_max': 0.2,
})
Serializers
Compression
Routing options
Callbacks
options = {
'link': app.signature('seal_pie'),
'link_error': app.signature('order_error')
}
for sub_task in options.values():
sub_task.set(
**app.amqp.router.route(sub_task.options, sub_task.task, sub_task.args,
sub_task.kwargs)
)
Periodic Tasks
from celery.schedule import crontab
CELERYBEAT_SCHEDULE = {
'check-every-minute': {
'task': 'check_ingredients',
'schedule':crontab()
}
$ celery -A pie_fabric beat
Concurrency
prefork (multiprocessing)
eventlet/gevent
threads/single threaded
Signals
Task Signals
App Signals
Worker Signals
Beat Signals
Eventlet Signals
Logging Signals
Command signals
Deprecated Signals
Worker Signals
celeryd_after_setup
celeryd_init
worker_init
worker_ready
worker_process_init
worker_process_shutdown
worker_shutdown
Ссылки
https://www.rabbitmq.com
http://docs.celeryproject.org
Cпасибо за внимание!
Вопросы?

More Related Content

What's hot

ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale
Subbu Allamaraju
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
MongoSF
 

What's hot (20)

Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and Lua
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
General Functions
General FunctionsGeneral Functions
General Functions
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기
 
Ricon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeRicon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak Pipe
 
ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
 
Kubernetes Tutorial
Kubernetes TutorialKubernetes Tutorial
Kubernetes Tutorial
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queue
 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Ubic
UbicUbic
Ubic
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbСтажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Feb14 successful development
Feb14 successful developmentFeb14 successful development
Feb14 successful development
 

Similar to Cooking pies with Celery

X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
Yiwei Ma
 
Nginx 0.8.x 安装手册
Nginx 0.8.x 安装手册Nginx 0.8.x 安装手册
Nginx 0.8.x 安装手册
Yiwei Ma
 
NLIT 2011: Chef & Capistrano
NLIT 2011: Chef & CapistranoNLIT 2011: Chef & Capistrano
NLIT 2011: Chef & Capistrano
nickblah
 
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLES
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLESQuick-and-Easy Deployment of a Ceph Storage Cluster with SLES
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLES
Jan Kalcic
 

Similar to Cooking pies with Celery (20)

Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Vagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptopVagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptop
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Sling Applications - A DevOps perspective
Sling Applications - A DevOps perspectiveSling Applications - A DevOps perspective
Sling Applications - A DevOps perspective
 
Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js Applications
 
Our Puppet Story – Patterns and Learnings (sage@guug, March 2014)
Our Puppet Story – Patterns and Learnings (sage@guug, March 2014)Our Puppet Story – Patterns and Learnings (sage@guug, March 2014)
Our Puppet Story – Patterns and Learnings (sage@guug, March 2014)
 
ONOS SDN Controller - Clustering Tests & Experiments
ONOS SDN Controller - Clustering Tests & Experiments ONOS SDN Controller - Clustering Tests & Experiments
ONOS SDN Controller - Clustering Tests & Experiments
 
Scaling Docker Containers using Kubernetes and Azure Container Service
Scaling Docker Containers using Kubernetes and Azure Container ServiceScaling Docker Containers using Kubernetes and Azure Container Service
Scaling Docker Containers using Kubernetes and Azure Container Service
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
Cloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the CloudCloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the Cloud
 
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all startedKernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
 
How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]
 
Nginx 0.8.x 安装手册
Nginx 0.8.x 安装手册Nginx 0.8.x 安装手册
Nginx 0.8.x 安装手册
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
NLIT 2011: Chef & Capistrano
NLIT 2011: Chef & CapistranoNLIT 2011: Chef & Capistrano
NLIT 2011: Chef & Capistrano
 
Tested install-isp config3-ubuntu-16-04
Tested install-isp config3-ubuntu-16-04Tested install-isp config3-ubuntu-16-04
Tested install-isp config3-ubuntu-16-04
 
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLES
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLESQuick-and-Easy Deployment of a Ceph Storage Cluster with SLES
Quick-and-Easy Deployment of a Ceph Storage Cluster with SLES
 

Recently uploaded

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

Cooking pies with Celery

  • 1. Печём пирожки с Celery Александр Мокров
  • 2. О чем доклад Немного об очередях Краткий обзор возможностей Celery Использование на примере виртуальной фабрики пирожков
  • 6. What is task queue?
  • 7. Celery: Distributed Task Queue Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. The execution units, called tasks, are executed concurrently on a single or more worker servers using multiprocessing, Eventlet, or gevent. Tasks can execute asynchronously (in the background) or synchronously (wait until ready). Celery is used in production systems to process millions of tasks a day.
  • 8.
  • 9. Ask Solem Hoel https://github.com/ask Principal Software Engineer at Robinhood San Francisco, CA Staff Engineer, RabbitMQ VMware май 2011 – май 2013 (2 года 1 месяц) Open source and consulting work on Celery, RabbitMQ, Celery Дата начала: май 2009
  • 10. Celery Kombu (Messaging library for Python) 41991 (22541) lines Billiard (Python multiprocessing fork with improvements and bugfixes) 19191(13115) Vine (promise, async, future) 2921 Celery 104296 (37495) Total 168399(76072)
  • 11. It supports Brokers RabbitMQ, Redis, MongoDB (exp), ZeroMQ (exp) CouchDB (exp), SQLAlchemy (exp) Django ORM (exp), Amazon SQS, (exp) Concurrency prefork (multiprocessing), Eventlet, gevent threads/single threaded Result Stores AMQP, Redis memcached, MongoDB SQLAlchemy, Django ORM Apache Cassandra Serialization pickle, json, yaml, msgpack. zlib, bzip2 compression. Cryptographic message signing
  • 12. Application from celery import Celery from conf import Settings from tasks.bake_pie import BakePie APP_NAME = 'pie_fabric' app = Celery(APP_NAME) app.config_from_object(Settings) app.tasks.register(BakePie())
  • 13. Settings class Settings: BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
  • 14. $ celery -A pie_fabric worker -l INFO -------------- celery@amokrov v4.0.0rc2 (0today8) ---- **** ----- --- * *** * -- Linux-3.19.0-61-generic-x86_64-with-Ubuntu-14.04-trusty 2016-06-24 15:52:22 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: pie_fabric:0x7efc8cd4c588 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: redis://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> celery exchange=celery(direct) key=celery [tasks] . bake_pie
  • 15. Architecture Client 1 Client 2 Worker 1Broker Task Queue 1 Task Queue 2 ... Worker 2 Result Backend send tasks send tasks tasks tasks task result task result get task result get task result
  • 17. Workflow get flour bake pie get meat seal pie create dough order pie get milk get aggs
  • 18. The canvas Wokrflow primitives ● group ● chain ● chord ● map, starmap, chunks
  • 19. Tasks from celery.app.task import Task from celery.utils.log import get_task_logger logger = get_task_logger(__name__) class GetIngredient(Task): name = 'get_ingredients' def run(self, ingredient_name): logger.info('Getting {}'.format(ingredient_name)) l # код получения ингредиента return ingredient
  • 20. Workflow from celery.app.task import Task from celery import canvas, signature class OrderPie(Task): name = 'order_pie' def run(self): get_meat = signature('get_ingredients', args=('meat',)) ... dough_chord = canvas.chord([get_eggs, get_milk, get_flour], create_dough) components_group = canvas.group(dough_chord, get_meat) return (components_group | seal_pie | bake_pie).delay()
  • 21. Client side >>> from tasks.order_pie import OrderPie >>> r = OrderPie().delay() >>> r.id '58c5bb47-8fb3-4d4a-b2f5-8899520b5179' >>> r.ready() True >>> r.get() [['091f9ae7-561a-4781-a4d9-47bbcb121360', [['0865f66b-b89d-4ff3-a272-1f6b01d0a11f', None], None]], None] >>> r.backend.get_task_meta(r.get()[0][0]) {'task_id': '091f9ae7-561a-4781-a4d9-47bbcb121360', 'children': [], 'traceback': None, 'result': 'baked pie with meat', 'status': 'SUCCESS'}
  • 22. Routing from kombu import Exchange, Queue class Router: def route_for_task(self, task, *args, **kwargs): route = {'exchange': Settings.EXCHANGE.name, 'routing_key': 'common'} if task in {'bake_pie', 'get_ingredients', 'seal_pie', 'order_pie'}: route['routing_key'] = 'fabric' elif task == 'create_dough': route = {'exchange': 'dough', 'routing_key': 'dough'} return route
  • 23. Routing class Settings: EXCHANGE = Exchange('pie_fabric, type='direct') CELERY_ROUTES = (Router(),) CELERY_QUEUES = ( Queue('pie_fabric.common', EXCHANGE, routing_key='common'), Queue('pie_fabric.fabric', EXCHANGE, routing_key='fabric'), ) --- ***** ----- [queues] -------------- .> pie_fabric.common exchange=pie_fabric(direct) key=common .> pie_fabric.fabric exchange=pie_fabric(direct) key=fabric
  • 24. Second application class Settings: BROKER_URL = 'amqp://guest:guest@localhost: 5672//' CELERY_RESULT_BACKEND = 'redis://127.0.0.1: 6379/0' EXCHANGE = Exchange('dough', type='direct') CELERY_QUEUES = ( Queue('dough', EXCHANGE, routing_key='dough'), ) app = Celery('dough') app.config_from_object(Settings) app.tasks.register(CreateDough()) $celery -A dough worker -P gevent -- concurrency=1000 -l INFO - ** ---------- [config] - ** ---------- .> app: dough:0x7f850ee22748 - ** ---------- .> transport: amqp://guest: **@localhost:5672// - ** ---------- .> results: redis://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 1000 (gevent) -- ******* ---- --- ***** ----- [queues] -------------- .> dough exchange=dough (direct) key=dough [tasks] . create_dough
  • 25. Gevent gevent is a coroutine -based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev event loop gevent.monkey – Make the standard library cooperative def _patch_gevent(): from gevent import monkey, signal as gsignal, version_info monkey.patch_all()
  • 26. Polling def run(self, *ingredients): logger.info('Ingredients: {}'.format(ingredients)) id = create_dough(ingredients) # Отправка запроса на приготовление теста while True: time.sleep(polling_timeout) if ready(id): # Проверяем готово ли тесто dough = get_dough(id) # Если готово, то забираем return dough
  • 27. Calling Tasks apply Execute this task locally, by blocking until the task returns. apply_async Apply tasks asynchronously by sending a message. delay Shortcut to send a task message, but does not support execution options. retry Retry the task.
  • 28. Options Linking (callbacks/errbacks) link link_error ETA and countdown countdown eta Expiration expires Retry retry=True, retry_policy={ 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2, }) Serializers Compression Routing options
  • 29. Callbacks options = { 'link': app.signature('seal_pie'), 'link_error': app.signature('order_error') } for sub_task in options.values(): sub_task.set( **app.amqp.router.route(sub_task.options, sub_task.task, sub_task.args, sub_task.kwargs) )
  • 30. Periodic Tasks from celery.schedule import crontab CELERYBEAT_SCHEDULE = { 'check-every-minute': { 'task': 'check_ingredients', 'schedule':crontab() } $ celery -A pie_fabric beat
  • 32. Signals Task Signals App Signals Worker Signals Beat Signals Eventlet Signals Logging Signals Command signals Deprecated Signals Worker Signals celeryd_after_setup celeryd_init worker_init worker_ready worker_process_init worker_process_shutdown worker_shutdown