Fabric 實踐:local 併發執行

環境:
fabric 服務器:10.10.1.1
目標服務器組:test.com (10.10.1.2-21)一共 20 臺服務器python

需求:api

我須要把我 fabric 服務器上的某些文件同步到 test.com 集羣,可是我又須要併發執行,而不是經過 for 循環或者是串行的方式。服務器

先直接上代碼再針對性的解釋:併發

#!/usr/bin/python env
#-*- coding: utf-8 -*-

from fabric.api import env
from fabric.api import run
from fabric.api import put
from fabric.api import execute
from fabric.api import roles
from fabric.api import parallel
from fabric.api import cd
from fabric.api import lcd
from fabric.api import task
from fabric.api import local
from fabric.api import settings
from fabric.api import hide
from fabric.colors import red ### 使輸出有色彩
from fabric.colors import green

### 下面這個角色在我實際的使用中,我是不須要填寫的,由於我實際使用是從 CMDB 動態獲取集羣的服務器列表的。爲了測試,因此弄了下面的

env.user = 'test'
env.password = 'test'
env.roledefs = {
   'test.com':['10.10.1.2','10.10.1.3','10.10.1.4','10.10.1.5',......],# 省略下,
}


######### reload data and rsync data###########
def rsync_test(host): ### 傳入 host 主機 IP 參數
    with settings(hide('running','stdout'), warn_only=True): ## hide 是表示不輸入信息到 sreen,能夠寫 'everything','stderr','running' 等等
        with lcd('/tmp/'):
           result = local('rsync -Pav test "%s":/tmp/' % host) ### 根據不一樣的主機 rsync 到不一樣的主機服務器
           if result.return_code == 0: ##能夠根據上面數據是否成功執行下一步操做。
               print (green("-------------------------"))
               print (red("*******主機 %s 同步數據成功******" % host))
               print (green("-------------------------"))
           else:
               print (green("-------------------------"))
               print (red("*******主機 %s 同步數據失敗******" % host))
               print (green("-------------------------"))

@task
@roles('test.com')
@parallel(pool_size=16)
def execute_rsync():
    execute(rsync_test, env.host) ### 讀取 @roles('test.com') 裏面的主機,並把 host 傳遞給 rsync_test 函數,而且 @parallel(pool_size=16) 來併發


@roles('test.com')
@parallel(pool_size=5)
def echo_hello():
    run('echo "hello world!"')

執行任務:ide

fab execute_rsync

輸出是:函數

#### 省略抹除了一些信息

同步數據成功******
-------------------------

Done.

real    0m1.263s
user    0m0.793s
sys     0m0.689s

若是沒有使用併發的話,執行時間爲:測試

-------------------------

Done.

real    0m3.680s
user    0m0.664s
sys     0m0.512s
相關文章
相關標籤/搜索