fabric初试

安装:

yum install -y python-pip openssl-devel python-devel python-pip libffi-devel libffi

pip install fabric

执行pip install fabric时自动安装的一些依赖包:

requirements:
asn1crypto-0.24.0 
bcrypt-3.1.4 
cffi-1.11.4 
cryptography-2.1.4 
enum34-1.1.6 
fabric-1.14.0 
ipaddress-1.0.19 
paramiko-2.4.0 
pyasn1-0.4.2 
pycparser-2.18 
pynacl-1.2.1

测试安装结果:

fab -h

安装时可能出现的异常:

Exception:

...
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 81, in _join_lingering_threads
    for thr in _active_threads:
TypeError: 'NoneType' object is not iterable
Error in sys.exitfunc:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 81, in _join_lingering_threads
    for thr in _active_threads:
TypeError: 'NoneType' object is not iterable

Resolve:

pip uninstall paramiko
pip install paramiko==1.18

Exception:

...

  File "/usr/lib64/python2.6/site-packages/Crypto/PublicKey/pubkey.py", line 30, in <module>
    from Crypto.Util.number import *
  File "/usr/lib64/python2.6/site-packages/Crypto/Util/number.py", line 56, in <module>
    if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
AttributeError: 'module' object has no attribute 'HAVE_DECL_MPZ_POWM_SEC'

Resolve:

rpm -qa |grep python-crypto
python-crypto-2.0.1-22.el6.x86_64
python-crypto2.6-2.6.1-2.el6.x86_64

rpm -qa |grep python-crypto |xargs yum remove -y

Exception:

# fab -h
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/fabric/network.py", line 24, in <module>
    import paramiko as ssh
  File "/usr/lib/python2.6/site-packages/paramiko/__init__.py", line 30, in <module>
    from paramiko.transport import SecurityOptions, Transport
  File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 51, in <module>
    from paramiko.dsskey import DSSKey
  File "/usr/lib/python2.6/site-packages/paramiko/dsskey.py", line 26, in <module>
    from Crypto.PublicKey import DSA
ImportError: No module named Crypto.PublicKey

There was a problem importing our SSH library (see traceback above).
Please make sure all dependencies are installed and importable.

Resolve:

# uninstall: pycrypto==2.6.1
pip uninstall pycrypto

# reinstall
pip install PyCrypto==2.3

一个fabfile.py例子

#! /usr/bin/evn python
# coding: utf-8

from fabric.api import local, run, env, cd, lcd, abort
from fabric.contrib.console import confirm
from fabric.operations import put
from fabric.colors import *
from datetime import datetime
from os import mkdir
from os.path import isdir, isfile
import shutil
import time

"""
xxxx

"""

# set envs:

service_list = [
"test-eureka", 
"test-server", 
"test-admin", 
"test-web"
]

code_dir = "xxxx"
pomfile = "{0}/parent/pom.xml".format(code_dir)
remote_sync_dir = "xxxx"
remote_service_dir = "xxxx"
backup_dir = "xxxx"

env.hosts = ['testserver:34562']
env.colorize_errors = True
# env.warn_only = True

def update_code():
    # on local
    print(yellow("Code Directory: " + code_dir))
    with lcd(code_dir):
        result = local("git checkout master && git pull")
        print(green('update coding ...'))

        if result.failed and not confirm("update code failed, Continue anyway?"):
            print(red("update code failed!"))
            abort("Aborting at user request.")
        else:
            print(green("update code success!"))
            result = local("git checkout release && git merge master")
            if result.failed and not confirm("checkout to release branch or merge code from master branch failed, Continue anyway?"):
                print(red("merge code failed!"))
                abort("Aborting at user request.")
            else:
                print(green("merge code success!"))
                result = local("git tag -f release{0} && git push --tags".format(datetime.now().strftime('%Y%m%d')))
                if result.failed and not confirm("make tag failed, Continue anyway?"):
                    print(red("make tag failed!"))
                    abort("Aborting at user request.")
                else:
                    print(green("make tag success!"))

def build():
    # on local
    # build jar
    with lcd(code_dir):
        result = local("git checkout release")
        # if result.failed and not confirm("update code failed, Continue anyway?"):
        local("ls")
        local("/var/lib/jenkins/tools/hudson.tasks.Maven_MavenInstallation/maven3.3.9/bin/mvn -f {0} clean deploy -Dmaven.test.skip=true".format(pomfile))

def backup():
    # on remote server
    latest_backup_dir = "{0}/{1}".format(backup_dir, datetime.now().strftime('%Y%m%d'))
    result = run("test -d {0}".format(latest_backup_dir))
    # if result.failed and not confirm("新的备份目录不存在,是否现在创建?"):
    if result.failed:
        print(yellow("The destination directory does not exist. will create it ..."))
        run("mkdir {0}".format(latest_backup_dir))
    with cd(remote_service_dir):
        for s in service_list:
            run('cp {0}/{0}.jar {1}'.format(s, latest_backup_dir))

def deploy():
    update_code()
    build()
    backup()
    with lcd(code_dir):
        put('{0}/jar/*.jar'.format(code_dir), remote_sync_dir)
    # deploy jar
    print ""
    print(yellow("  Deployment sevices ..."))
    print ""
    with cd(remote_service_dir):
        for service_name in service_list:
            run('cp {0}/{1}.jar ./{1}'.format(remote_sync_dir, service_name))
            # restart service
            result = run('screen -ls | grep -w {0} | cut -f 2'.format(service_name))
            if not result == '':
                run("screen -r {0} -p 0 -X stuff 'exit' && screen -r {0} -p 0 -X stuff $'\n'".format(service_name))
                time.sleep(3)
                print(yellow(" {0}: has exited! ".format(service_name)))
                # run("screen -r {0} -p 0 -X stuff './startup.sh' && screen -r {0} -p 0 -X stuff $'\n'".format(service_name))
                run("cd /data/product/release/{0} && screen -dmS {0} && screen -r {0} -p 0 -X stuff './startup.sh' && screen -r {0} -p 0 -X stuff $'\n'".format(service_name))
                print(green(" {0}: has started! ".format(service_name)))
            else:
                run("cd /data/product/release/{0} && screen -dmS {0} && screen -r {0} -p 0 -X stuff './startup.sh' && screen -r {0} -p 0 -X stuff $'\n'".format(service_name))
                print(green(" {0}: has started! ".format(service_name)))


#if __name__=="__main__":
#    deploy()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值