Ansible源碼分析之svn模塊-創(chuàng)新互聯(lián)

Ansible的svn模塊代碼路徑

創(chuàng)新互聯(lián)成立于2013年,先為鐵東等服務(wù)建站,鐵東等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為鐵東企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

/usr/lib/python2.6/site-packages/ansible/modules/core/source_control

模塊使用:

# ansible localhost -m subversion -a "repo=https://code.svn.com/project1/patch_04 dest=~/test username=test password=test123   export=yes force=yes"

-m subversion表示指定subversion模塊,這里的模塊名稱都是modules目錄下的腳本名稱

-a 指定模塊參數(shù),每個(gè)模塊的參數(shù)不同

repo 指定svn的URL

dest 指定代碼checkout或者export的絕對(duì)路徑

username 指定用戶名

password 指定密碼

export 指定導(dǎo)出而不是checkout或者update

force 強(qiáng)制執(zhí)行

如果執(zhí)行過程有以下錯(cuò)誤

"msg": "svn: Can't convert string from 'UTF-8' to native encoding:\nsvn: /root/john/test/web/WebRoot/html/?\\230?\\181?\\160?\\239?\\189?\\135?\\230?\\130?\\138",

解決辦法就是:

將系統(tǒng)的字符編號(hào)和ansible的字符編號(hào)都設(shè)置成en_US.UTF-8

# echo $LANG
en_US.UTF-8
# cat /etc/ansible/ansible.cfg|grep module_lang
module_lang    = en_US.UTF-8

同時(shí)在subversion.py中設(shè)置的默認(rèn)字符編碼就是C

os.environ['LANG'] = 'C'

class Subversion(object):
    def __init__(
            self, module, dest, repo, revision, username, password, svn_path):
        self.module = module
        self.dest = dest
        self.repo = repo
        self.revision = revision
        self.username = username
        self.password = password
        self.svn_path = svn_path

定義一個(gè)Python類Subversion和一些類參數(shù)

def _exec(self, args):
        bits = [
            self.svn_path,
            '--non-interactive',
            '--trust-server-cert',
            '--no-auth-cache',
        ]
        if self.username:
            bits.extend(["--username", self.username])
        if self.password:
            bits.extend(["--password", self.password])
        bits.extend(args)
        rc, out, err = self.module.run_command(bits, check_rc=True)
        return out.splitlines()

定義類函數(shù)_exec,調(diào)用module_utils/basic.py中的run_command 函數(shù)

 def checkout(self):
        '''Creates new svn working directory if it does not already exist.'''
        self._exec(["checkout", "-r", self.revision, self.repo, self.dest])

 def export(self, force=False):
        '''Export svn repo to directory'''
        cmd = ["export"]
        if force:
            cmd.append("--force")
        cmd.extend(["-r", self.revision, self.repo, self.dest])

        self._exec(cmd)

定義checkout和export函數(shù),分別執(zhí)行svn checkout 或者svn export

    def switch(self):
        '''Change working directory's repo.'''
        # switch to ensure we are pointing at correct repo.
        self._exec(["switch", self.repo, self.dest])

    def update(self):
        '''Update existing svn working directory.'''
        self._exec(["update", "-r", self.revision, self.dest])

    def revert(self):
        '''Revert svn working directory.'''
        self._exec(["revert", "-R", self.dest])

    def get_revision(self):
        '''Revision and URL of subversion working directory.'''
        text = '\n'.join(self._exec(["info", self.dest]))
        rev = re.search(r'^Revision:.*$', text, re.MULTILINE).group(0)
        url = re.search(r'^URL:.*$', text, re.MULTILINE).group(0)
        return rev, url

定義svn switch, svn update,svn revert,svn get_revision相關(guān)的函數(shù)

    def has_local_mods(self):
        '''True if revisioned files have been added or modified. Unrevisioned files are ignored.'''
        lines = self._exec(["status", self.dest])
        # Match only revisioned files, i.e. ignore status '?'.
        regex = re.compile(r'^[^?]')
        # Has local mods if more than 0 modifed revisioned files.
        return len(filter(regex.match, lines)) > 0

    def needs_update(self):
        curr, url = self.get_revision()
        out2 = '\n'.join(self._exec(["info", "-r", "HEAD", self.dest]))
        head = re.search(r'^Revision:.*$', out2, re.MULTILINE).group(0)
        rev1 = int(curr.split(':')[1].strip())
        rev2 = int(head.split(':')[1].strip())
        change = False
        if rev1 < rev2:
            change = True
        return change, curr, head

兩個(gè)函數(shù)執(zhí)行svn status 和svn info

def main():
    module = AnsibleModule(
        argument_spec=dict(
            dest=dict(required=True),
            repo=dict(required=True, aliases=['name', 'repository']),
            revision=dict(default='HEAD', aliases=['rev', 'version']),
            force=dict(default='no', type='bool'),
            username=dict(required=False),
            password=dict(required=False),
            executable=dict(default=None),
            export=dict(default=False, required=False, type='bool'),
        ),
        supports_check_mode=True
    )

    dest = os.path.expanduser(module.params['dest'])
    repo = module.params['repo']
    revision = module.params['revision']
    force = module.params['force']
    username = module.params['username']
    password = module.params['password']
    svn_path = module.params['executable'] or module.get_bin_path('svn', True)
    export = module.params['export']

    os.environ['LANG'] = 'C'
    svn = Subversion(module, dest, repo, revision, username, password, svn_path)

    if export or not os.path.exists(dest):
        before = None
        local_mods = False
        if module.check_mode:
            module.exit_json(changed=True)
        if not export:
            svn.checkout()
        else:
            svn.export(force=force)
    elif os.path.exists("%s/.svn" % (dest, )):
        # Order matters. Need to get local mods before switch to avoid false
        # positives. Need to switch before revert to ensure we are reverting to
        # correct repo.
        if module.check_mode:
            check, before, after = svn.needs_update()
            module.exit_json(changed=check, before=before, after=after)
        before = svn.get_revision()
        local_mods = svn.has_local_mods()
        svn.switch()
        if local_mods:
            if force:
                svn.revert()
            else:
                module.fail_json(msg="ERROR: modified files exist in the repository.")
        svn.update()
    else:
        module.fail_json(msg="ERROR: %s folder already exists, but its not a subversion repository." % (dest, ))

    if export:
        module.exit_json(changed=True)
    else:
        after = svn.get_revision()
        changed = before != after or local_mods
        module.exit_json(changed=changed, before=before, after=after)

# import module snippets
from ansible.module_utils.basic import *
main()

這里就是svn模塊的main函數(shù),先判斷是export還是checkout,再判斷dest指定的目錄是否存在,再判斷版本有沒有更新

參考文檔:

https://github.com/ansible/ansible/issues/6737#ref-commit-42aa6ff

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

文章名稱:Ansible源碼分析之svn模塊-創(chuàng)新互聯(lián)
當(dāng)前地址:http://bm7419.com/article12/cdghgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、網(wǎng)站收錄、定制開發(fā)網(wǎng)站營銷、電子商務(wù)網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)