Last active
September 5, 2017 15:25
-
-
Save thefish/36cd2b223a0158977e75124d55e752f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# Simple example which uses a pool of workers to carry out some tasks. | |
# | |
# Notice that the results will probably not come out of the output | |
# queue in the same in the same order as the corresponding tasks were | |
# put on the input queue. If it is important to get the results back | |
# in the original order then consider using `Pool.map()` or | |
# `Pool.imap()` (which will save on the amount of code needed anyway). | |
# | |
# Copyright (c) 2006-2008, R Oudkerk | |
# All rights reserved. | |
# | |
import time | |
import random | |
from multiprocessing import Process, Queue, current_process, freeze_support | |
# | |
# Function run by worker processes | |
# | |
def worker(input, output): | |
for func, args in iter(input.get, 'STOP'): | |
result = execute(func, args) | |
output.put(result) | |
# | |
# Function used to calculate result | |
# | |
def execute(func, args): | |
result = func(*args) | |
return '%s running task %s%s reports: \t\t %s' % \ | |
(current_process().name, func.__name__, args, result) | |
# | |
# Functions referenced by tasks | |
# | |
# Тут функции чисто для примера, их лучше в отдельные модули вынести | |
# | |
def prepare(machine): | |
# подготовка машины к деплою (удаляем, мувим всю ненужную хуйню) | |
time.sleep(0.5*random.random()) | |
# Здесь вместо строчки можно вернуть код выполнения чтобы понять нормально ли всё прошло | |
# или использовать отдельную error_queue для паник, например | |
return "... preparing " + machine | |
def deploy(package, machine): | |
# Установка пакетов | |
time.sleep(0.5*random.random()) | |
return "... deploying " + package + " to " + machine | |
def setup(package, machine): | |
# Настройка пакетов | |
time.sleep(0.5*random.random()) | |
return "... setting up " + package + " on " + machine | |
# | |
# | |
# | |
def main(): | |
# В сколько процессов ебашим | |
NUMBER_OF_PROCESSES = 4 | |
# Что ставим | |
PACKAGES = ["nginx", "postfix", "fpm"] | |
# Куда ставим | |
SERVERS = ["front01", "front02", "front03", "front04", "front05"] | |
#Тут можно не генеренные списки пихать, а прям руками написать, если надо | |
TASKS1 = [(prepare, (server, )) for server in SERVERS] | |
# Вторая пачка задач | |
TASKS2 = [(deploy, (package, server)) for package in PACKAGES for server in SERVERS] | |
TASKS3 = [(setup, (package, server)) for package in PACKAGES for server in SERVERS] | |
# Create queues | |
task_queue = Queue() | |
done_queue = Queue() | |
# Submit tasks | |
# Шлем первую пачку | |
for task in TASKS1: | |
task_queue.put(task) | |
# Start worker processes | |
for i in range(NUMBER_OF_PROCESSES): | |
Process(target=worker, args=(task_queue, done_queue)).start() | |
# Get and print results | |
# Получаем результат выполнения, и если | |
# надо - обрабатываем (откатываем всё взад например если функция вернула что-то не то) | |
print 'Unordered results:' | |
for i in range(len(TASKS1)): | |
print '\t', done_queue.get() | |
# Вторая пачка пошла | |
# Add more tasks using `put()` | |
for task in TASKS2: | |
task_queue.put(task) | |
# Get and print some more results | |
# Получаем результат | |
for i in range(len(TASKS2)): | |
print '\t', done_queue.get() | |
# Пример - если надо что-то выполнить,не запуская следующий этап | |
print "Waiting..." | |
# выполняем | |
time.sleep(3) | |
for task in TASKS3: | |
task_queue.put(task) | |
# Get and print some more results | |
# Получаем результат | |
for i in range(len(TASKS3)): | |
print '\t', done_queue.get() | |
# Tell child processes to stop | |
# Стопаем всю хуйню, готово | |
for i in range(NUMBER_OF_PROCESSES): | |
task_queue.put('STOP') | |
if __name__ == '__main__': | |
freeze_support() | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment